
// ================================
// 全局变量和配置
// ================================
const apiBase = location.origin;
let keywordsData = {};
let currentCookieId = '';
let editCookieId = '';
let authToken = localStorage.getItem('auth_token');
let dashboardData = {
    accounts: [],
    totalKeywords: 0
};

// 账号关键词缓存
let accountKeywordCache = {};
let cacheTimestamp = 0;
const CACHE_DURATION = 30000; // 30秒缓存

// 关键词分页相关变量
let currentKeywordsPage = 1;
let keywordsPageSize = 50;
let totalKeywordsCount = 0;
let totalKeywordsPages = 0;

// ================================
// 性能优化工具函数
// ================================

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 节流函数
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    }
}

// 防抖的账号列表刷新
const debouncedRefreshAccountList = debounce(refreshAccountList, 1000);

// 防抖的搜索函数
const debouncedKeywordSearch = debounce(function(searchTerm) {
    if (!currentCookieId || !keywordsData[currentCookieId]) return;
    
    const keywords = keywordsData[currentCookieId];
    const filteredKeywords = keywords.filter(keyword => {
        const keywordMatch = keyword.keyword.toLowerCase().includes(searchTerm.toLowerCase());
        const itemIdMatch = keyword.item_id && keyword.item_id.toLowerCase().includes(searchTerm.toLowerCase());
        const replyMatch = keyword.reply && keyword.reply.toLowerCase().includes(searchTerm.toLowerCase());
        return keywordMatch || itemIdMatch || replyMatch;
    });
    
    renderKeywordsList(filteredKeywords);
    
    // 更新搜索结果信息
    const searchResultsText = document.getElementById('searchResultsText');
    if (searchResultsText) {
        searchResultsText.textContent = `找到 ${filteredKeywords.length} 个匹配 "${searchTerm}" 的关键词`;
    }
}, 300);

// 商品列表搜索和分页相关变量
let allItemsData = []; // 存储所有商品数据
let filteredItemsData = []; // 存储过滤后的商品数据
let currentItemsPage = 1; // 当前页码
let itemsPerPage = 20; // 每页显示数量
let totalItemsPages = 0; // 总页数
let currentSearchKeyword = ''; // 当前搜索关键词

// ================================
// 通用功能 - 菜单切换和导航
// ================================
function showSection(sectionName) {
    console.log('切换到页面:', sectionName); // 调试信息

    // 隐藏所有内容区域
    document.querySelectorAll('.content-section').forEach(section => {
    section.classList.remove('active');
    });

    // 移除所有菜单项的active状态
    document.querySelectorAll('.nav-link').forEach(link => {
    link.classList.remove('active');
    });

    // 显示选中的内容区域
    const targetSection = document.getElementById(sectionName + '-section');
    if (targetSection) {
    targetSection.classList.add('active');
    console.log('页面已激活:', sectionName + '-section'); // 调试信息
    } else {
    console.error('找不到页面元素:', sectionName + '-section'); // 调试信息
    }

    // 设置对应菜单项为active（修复event.target问题）
    const menuLinks = document.querySelectorAll('.nav-link');
    menuLinks.forEach(link => {
    if (link.onclick && link.onclick.toString().includes(`showSection('${sectionName}')`)) {
        link.classList.add('active');
    }
    });

    // 根据不同section加载对应数据
    switch(sectionName) {
    case 'dashboard':        // 【仪表盘菜单】
        loadDashboard();
        break;
    case 'accounts':         // 【账号管理菜单】
        loadCookies();
        break;
    case 'items':           // 【商品管理菜单】
        loadItems();
        break;
    case 'auto-reply':      // 【自动回复菜单】
        refreshAccountList();
        break;
    case 'cards':           // 【卡种管理菜单】
        loadCards();
        break;
    case 'auto-delivery':   // 【自动发货菜单】
        loadDeliveryRules();
        break;
    case 'notification-channels':  // 【通知渠道菜单】
        loadNotificationChannels();
        break;
    case 'message-notifications':  // 【消息通知菜单】
        loadMessageNotifications();
        break;
    case 'system-settings':    // 【系统设置菜单】
        loadSystemSettings();
        break;
    case 'personal-info':      // 【个人信息菜单】
        loadPersonalInfo();
        break;
    case 'keyword-library':    // 【门店词库菜单】
        loadKeywordLibraries();
        break;
    case 'global-keywords':    // 【通用词库菜单】
        loadGlobalKeywords();
        break;
    case 'logs':            // 【日志管理菜单】
        // 如果没有日志数据，则加载
        setTimeout(() => {
        if (!window.allLogs || window.allLogs.length === 0) {
            refreshLogs();
        }
        }, 100);
        break;
    }

    // 如果切换到非日志页面，停止自动刷新
    if (sectionName !== 'logs' && window.autoRefreshInterval) {
    clearInterval(window.autoRefreshInterval);
    window.autoRefreshInterval = null;
    const button = document.querySelector('#autoRefreshText');
    const icon = button?.previousElementSibling;
    if (button) {
        button.textContent = '开启自动刷新';
        if (icon) icon.className = 'bi bi-play-circle me-1';
    }
    }
}

// 移动端侧边栏切换
function toggleSidebar() {
    document.getElementById('sidebar').classList.toggle('show');
}

// ================================
// 【仪表盘菜单】相关功能
// ================================

// 加载仪表盘数据
async function loadDashboard() {
    try {
    toggleLoading(true);

    // 并行获取账号列表和统计数据
    const [cookiesResponse, statsResponse] = await Promise.all([
        fetch(`${apiBase}/cookies/details-optimized`, {
            headers: { 'Authorization': `Bearer ${authToken}` }
        }),
        fetch(`${apiBase}/dashboard/stats`, {
            headers: { 'Authorization': `Bearer ${authToken}` }
        })
    ]);

    if (cookiesResponse.ok) {
        const accountsWithKeywords = await cookiesResponse.json();
        dashboardData.accounts = accountsWithKeywords;

        // 使用服务端统计数据（如果可用）
        if (statsResponse.ok) {
            const statsData = await statsResponse.json();
            if (statsData.success) {
                const stats = statsData.data;
                dashboardData.totalKeywords = stats.total_keywords;
                
                // 更新仪表盘显示
                updateDashboardStats(stats.total_accounts, stats.total_keywords, stats.enabled_accounts);
                updateDashboardAccountsList(accountsWithKeywords);
                return;
            }
        }

        // 降级到客户端计算
        let totalKeywords = 0;
        let activeAccounts = 0;
        let enabledAccounts = 0;

        accountsWithKeywords.forEach(account => {
            // 统一使用keyword_count字段
            const keywordCount = account.keyword_count || account.keywordCount || 0;
            const isEnabled = account.enabled === undefined ? true : account.enabled;

            if (isEnabled) {
                enabledAccounts++;
                totalKeywords += keywordCount;
                if (keywordCount > 0) {
                    activeAccounts++;
                }
            }
        });

        dashboardData.totalKeywords = totalKeywords;

        // 更新仪表盘显示
        updateDashboardStats(accountsWithKeywords.length, totalKeywords, enabledAccounts);
        updateDashboardAccountsList(accountsWithKeywords);
    }
    } catch (error) {
    console.error('加载仪表盘数据失败:', error);
    showToast('加载仪表盘数据失败', 'danger');
    } finally {
    toggleLoading(false);
    }
}

// 更新仪表盘统计数据
function updateDashboardStats(totalAccounts, totalKeywords, enabledAccounts) {
    document.getElementById('totalAccounts').textContent = totalAccounts;
    document.getElementById('activeAccounts').textContent = enabledAccounts;
}

// 更新仪表盘账号列表
function updateDashboardAccountsList(accounts) {
    const tbody = document.getElementById('dashboardAccountsList');
    tbody.innerHTML = '';

    if (accounts.length === 0) {
    tbody.innerHTML = `
        <tr>
        <td colspan="4" class="text-center text-muted py-4">
            <i class="bi bi-inbox fs-1 d-block mb-2"></i>
            暂无账号数据
        </td>
        </tr>
    `;
    return;
    }

    accounts.forEach(account => {
    // 使用正确的字段名（统一使用keyword_count）
    const keywordCount = account.keyword_count || account.keywordCount || 0;
    const isEnabled = account.enabled === undefined ? true : account.enabled;

    let status = '';
    if (!isEnabled) {
        status = '<span class="badge bg-danger">已禁用</span>';
    } else if (keywordCount > 0) {
        status = '<span class="badge bg-success">活跃</span>';
    } else {
        status = '<span class="badge bg-secondary">未配置</span>';
    }

    const row = document.createElement('tr');
    row.className = isEnabled ? '' : 'table-secondary';
    row.innerHTML = `
        <td>
        <strong class="text-primary ${!isEnabled ? 'text-muted' : ''}">${account.id}</strong>
        ${!isEnabled ? '<i class="bi bi-pause-circle-fill text-danger ms-1" title="已禁用"></i>' : ''}
        </td>
        <td>
        <span class="badge ${isEnabled ? 'bg-primary' : 'bg-secondary'}">${keywordCount} 个关键词</span>
        </td>
        <td>${status}</td>
        <td>
        <small class="text-muted">${new Date().toLocaleString()}</small>
        </td>
    `;
    tbody.appendChild(row);
    });
}

// 获取账号关键词数量（带缓存）- 包含普通关键词和商品关键词
async function getAccountKeywordCount(accountId) {
    const now = Date.now();

    // 检查缓存
    if (accountKeywordCache[accountId] && (now - cacheTimestamp) < CACHE_DURATION) {
    return accountKeywordCache[accountId];
    }

    try {
    const response = await fetch(`${apiBase}/keywords/${accountId}`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        const keywordsData = await response.json();
        // 现在API返回的是包含普通关键词和商品关键词的完整列表
        const count = keywordsData.length;

        // 更新缓存
        accountKeywordCache[accountId] = count;
        cacheTimestamp = now;

        return count;
    } else {
        return 0;
    }
    } catch (error) {
    console.error(`获取账号 ${accountId} 关键词失败:`, error);
    return 0;
    }
}

// 清除关键词缓存
function clearKeywordCache() {
    accountKeywordCache = {};
    cacheTimestamp = 0;
}

// ================================
// 【自动回复菜单】相关功能
// ================================

// 刷新账号列表（用于自动回复页面）
async function refreshAccountList() {
    try {
        toggleLoading(true);
        
        // 初始化时隐藏关键词管理区域
        const keywordManagement = document.getElementById('keywordManagement');
        if (keywordManagement) {
            keywordManagement.style.display = 'none';
        }

    // 使用优化的API获取账号列表（已包含关键词统计）
    const response = await fetch(`${apiBase}/cookies/details-optimized`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        const accountsWithKeywords = await response.json();
        const select = document.getElementById('accountSelect');
        select.innerHTML = '<option value="">🔍 请选择一个账号开始配置...</option>';

        // 数据已经包含关键词统计，不需要额外请求

        // 渲染账号选项（显示所有账号，但标识禁用状态）
        if (accountsWithKeywords.length === 0) {
        select.innerHTML = '<option value="">❌ 暂无账号，请先添加账号</option>';
        return;
        }

        // 分组显示：先显示启用的账号，再显示禁用的账号
        const enabledAccounts = accountsWithKeywords.filter(account => {
        const enabled = account.enabled === undefined ? true : account.enabled;
        console.log(`账号 ${account.id} 过滤状态: enabled=${account.enabled}, 判断为启用=${enabled}`); // 调试信息
        return enabled;
        });
        const disabledAccounts = accountsWithKeywords.filter(account => {
        const enabled = account.enabled === undefined ? true : account.enabled;
        return !enabled;
        });

        // 渲染启用的账号
        enabledAccounts.forEach(account => {
        const option = document.createElement('option');
        option.value = account.id;

        // 根据已配置商品数量显示不同的图标和样式
        let icon = '📝';
        let status = '';
        const itemsCount = account.items_count || 0;
        if (itemsCount === 0) {
            icon = '⚪';
            status = ' (未配置)';
        } else if (itemsCount >= 5) {
            icon = '🟢';
            status = ` (已配置 ${itemsCount} 个商品)`;
        } else {
            icon = '🟡';
            status = ` (已配置 ${itemsCount} 个商品)`;
        }

        // 构建显示文本：图标 + 账号ID + 备注名 + 状态
        let displayText = `${icon} ${account.id}`;
        
        // 如果有备注名，添加到显示文本中
        if (account.remark && account.remark.trim()) {
            displayText += ` - ${account.remark.trim()}`;
        }
        
        displayText += status;
        option.textContent = displayText;
        select.appendChild(option);
        });

        // 如果有禁用的账号，添加分隔线和禁用账号
        if (disabledAccounts.length > 0) {
        // 添加分隔线
        const separatorOption = document.createElement('option');
        separatorOption.disabled = true;
        separatorOption.textContent = `--- 禁用账号 (${disabledAccounts.length} 个) ---`;
        select.appendChild(separatorOption);

        // 渲染禁用的账号
        disabledAccounts.forEach(account => {
            const option = document.createElement('option');
            option.value = account.id;

            // 禁用账号使用特殊图标和样式
            let icon = '🔴';
            let status = '';
            const itemsCount = account.items_count || 0;
            if (itemsCount === 0) {
            status = ' (未配置) [已禁用]';
            } else {
            status = ` (已配置 ${itemsCount} 个商品) [已禁用]`;
            }

            // 构建显示文本：图标 + 账号ID + 备注名 + 状态
            let displayText = `${icon} ${account.id}`;
            
            // 如果有备注名，添加到显示文本中
            if (account.remark && account.remark.trim()) {
                displayText += ` - ${account.remark.trim()}`;
            }
            
            displayText += status;
            option.textContent = displayText;
            option.style.color = '#6b7280';
            option.style.fontStyle = 'italic';
            select.appendChild(option);
        });
        }

        console.log('账号列表刷新完成，关键词统计:', accountsWithKeywords.map(a => ({id: a.id, keywords: a.keyword_count})));
    } else {
        showToast('获取账号列表失败', 'danger');
    }
    } catch (error) {
    console.error('刷新账号列表失败:', error);
    showToast('刷新账号列表失败', 'danger');
    } finally {
    toggleLoading(false);
    }
}

// 只刷新关键词列表（不重新加载商品列表等其他数据）
async function refreshKeywordsList() {
    if (!currentCookieId) {
        console.warn('没有选中的账号，无法刷新关键词列表');
        return;
    }

    // 检查用户权限
    const hasManagePermission = hasAutoReplyManagePermission();

    try {
        if (hasManagePermission) {
            // 管理员：刷新关键词列表
            if (isSearching) {
                // 搜索状态下，重新执行搜索
                await performKeywordSearch(currentSearchTerm);
            } else {
                // 正常状态下，刷新当前页
                await loadKeywordsPage(currentKeywordsPage);
            }
            // 清除关键词缓存
            clearKeywordCache();
        } else {
            // 普通用户：刷新已配置商品列表
            await loadConfiguredItems(currentCookieId);
        }
    } catch (error) {
        console.error('刷新列表失败:', error);
        showToast('刷新列表失败', 'danger');
    }
}

// 加载账号关键词（使用分页）
async function loadAccountKeywords() {
    const accountId = document.getElementById('accountSelect').value;
    const keywordManagement = document.getElementById('keywordManagement');

    if (!accountId) {
        keywordManagement.style.display = 'none';
        return;
    }

    try {
        toggleLoading(true);
        currentCookieId = accountId;
        
        // 切换账号时重置分页和搜索状态
        currentKeywordsPage = 1;
        resetSearchState();

        // 获取账号详情以检查状态
        const accountResponse = await fetch(`${apiBase}/cookies/details`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });

        let accountStatus = true; // 默认启用
        if (accountResponse.ok) {
            const accounts = await accountResponse.json();
            const currentAccount = accounts.find(acc => acc.id === accountId);
            accountStatus = currentAccount ? (currentAccount.enabled === undefined ? true : currentAccount.enabled) : true;
            console.log(`加载关键词时账号 ${accountId} 状态: enabled=${currentAccount?.enabled}, accountStatus=${accountStatus}`);
        }

        // 检查用户权限（管理员或有auto_reply_manage权限的用户可以管理关键词）
        const hasManagePermission = hasAutoReplyManagePermission();

        // 先根据权限更新UI
        updateKeywordManagementUI(hasManagePermission);

        if (hasManagePermission) {
            // 管理员：加载完整的关键词数据
            await loadKeywordsPage(1);
            // 加载商品列表
            await loadItemsList(accountId);
            // 管理员：独立加载所有商品ID汇总信息
            await loadAllItemIdsSummary(accountId);
        } else {
            // 普通用户：只加载已配置自动回复的商品信息
            await loadConfiguredItems(accountId);
        }

        // 更新账号徽章显示
        updateAccountBadge(accountId, accountStatus);

        // 显示关键词管理容器（但内容根据权限控制）
        keywordManagement.style.display = 'block';
    } catch (error) {
        console.error('加载关键词失败:', error);
        showToast('加载关键词失败', 'danger');
    } finally {
        toggleLoading(false);
    }
}

// 从关键词数据中提取已配置的商品信息
function extractConfiguredItems(keywords) {
    const itemsMap = new Map();
    
    keywords.forEach(keyword => {
        if (keyword.item_id && keyword.item_id.trim()) {
            const itemId = keyword.item_id.trim();
            if (!itemsMap.has(itemId)) {
                itemsMap.set(itemId, {
                    item_id: itemId,
                    item_title: `商品 ${itemId}`, // 默认标题，实际可能需要从其他接口获取
                    keyword_count: 0,
                    libraries: new Set() // 用于收集词库信息
                });
            }
            const item = itemsMap.get(itemId);
            item.keyword_count++;
            
            // 收集词库信息
            if (keyword.library_name) {
                item.libraries.add(keyword.library_name);
            }
        }
    });
    
    // 将Set转换为数组
    const items = Array.from(itemsMap.values());
    items.forEach(item => {
        item.libraries = Array.from(item.libraries);
    });
    
    return items;
}

// 加载已配置自动回复的商品信息（普通用户）
async function loadConfiguredItems(accountId) {
    console.log(`loadConfiguredItems 被调用，账号ID: ${accountId}`);
    try {
        const response = await fetch(`${apiBase}/keywords/${accountId}`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });

        if (response.ok) {
            const data = await response.json();
            console.log('普通用户获取已配置商品数据:', data);
            console.log('数据类型:', typeof data, '是否为数组:', Array.isArray(data), '数据长度:', data.length);
            
            // 详细打印每个商品的信息
            if (Array.isArray(data)) {
                data.forEach((item, index) => {
                    console.log(`商品 ${index + 1}: ID=${item.item_id}, 标题=${item.item_title}, 词库=${JSON.stringify(item.libraries)}`);
                });
            }

            if (Array.isArray(data)) {
                // 存储关键词数据供其他函数使用
                keywordsData[accountId] = data;
                
                if (data.length > 0) {
                    console.log('准备渲染商品列表，数据:', data);
                    // 普通用户的数据已经是处理好的商品信息，直接渲染
                    renderConfiguredItemsList(data);
                } else {
                    // 没有关键词数据
                    renderConfiguredItemsList([]);
                }
            } else {
                showToast('获取已配置商品信息失败', 'danger');
            }
        } else {
            showToast('获取已配置商品信息失败', 'danger');
        }
    } catch (error) {
        console.error('加载已配置商品失败:', error);
        showToast('加载已配置商品失败', 'danger');
    }
}

// 管理员：加载所有商品ID汇总信息
async function loadAllItemIdsSummary(accountId) {
    console.log(`loadAllItemIdsSummary 被调用，账号ID: ${accountId}`);
    try {
        // 使用优化的API获取商品汇总信息，避免获取完整的关键词内容
        const response = await fetch(`${apiBase}/keywords/${accountId}/items-summary`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });

        if (response.ok) {
            const itemsSummary = await response.json();
            console.log('管理员获取商品ID汇总数据:', itemsSummary);
            
            if (Array.isArray(itemsSummary) && itemsSummary.length > 0) {
                console.log(`管理员视图：获取到 ${itemsSummary.length} 个商品汇总`);
                
                // 数据已经是汇总格式，直接使用
                console.log('管理员商品汇总:', itemsSummary);
                
                // 使用管理员版本的渲染函数
                renderAdminItemIdsList(itemsSummary);
            } else {
                renderAdminItemIdsList([]);
            }
        } else {
            console.error('获取商品ID汇总信息失败:', response.status);
            renderAdminItemIdsList([]);
        }
    } catch (error) {
        console.error('加载商品ID汇总信息失败:', error);
        renderAdminItemIdsList([]);
    }
}

// 渲染管理员版本的商品ID列表（显示所有商品）
function renderAdminItemIdsList(itemsSummary) {
    console.log('renderAdminItemIdsList 被调用，数据:', itemsSummary);
    
    const itemIdsGrid = document.getElementById('itemIdsGrid');
    const itemIdsCount = document.getElementById('itemIdsCount');
    const itemIdsContainer = document.getElementById('itemIdsContainer');
    
    if (!itemIdsGrid || !itemIdsContainer) {
        console.error('商品ID容器元素未找到');
        return;
    }
    
    // 清空容器
    itemIdsGrid.innerHTML = '';
    
    if (!itemsSummary || itemsSummary.length === 0) {
        itemIdsGrid.innerHTML = `
            <div class="text-center p-5 text-muted">
                <i class="bi bi-box-seam fs-1 mb-3"></i>
                <h5 class="mb-2">暂无已配置自动回复的商品</h5>
                <p class="mb-0">当前账号还没有为任何商品配置自动回复</p>
            </div>
        `;
        // 更新商品数量显示
        const itemIdsCountElements = document.querySelectorAll('#itemIdsCount, [id="itemIdsCount"]');
        itemIdsCountElements.forEach(element => {
            if (element) {
                element.textContent = '0 个商品';
            }
        });
    } else {
        console.log(`开始渲染管理员商品列表，共 ${itemsSummary.length} 个商品`);
        
        // 为每个商品创建卡片元素
        itemsSummary.forEach((item, index) => {
            try {
                console.log(`渲染管理员商品 ${index + 1}: ${item.item_id}`);
                const cardElement = document.createElement('div');
                cardElement.className = 'item-id-card';
                cardElement.setAttribute('data-item-id', item.item_id);
                
                // 生成关键词标签（显示数量）
                const keywordTags = `<span class="item-id-count">已配置自动回复</span>`;
                
                // 生成词库信息标签
                const libraryTags = item.libraries && item.libraries.length > 0 ? `
                    <div class="item-id-libraries">
                        <small class="text-info">
                            <i class="bi bi-collection me-1"></i>
                            词库: ${item.libraries.map(lib => `<span class="badge bg-info">${escapeHtml(lib)}</span>`).join(' ')}
                        </small>
                    </div>
                ` : '';
                
                cardElement.innerHTML = `
                    <div class="item-id-header">
                        <div class="item-id-title">
                            <i class="bi bi-box"></i>
                            商品ID
                            <span class="item-id-value">${escapeHtml(item.item_id)}</span>
                        </div>
                        <div class="item-id-actions">
                            <button class="btn btn-sm btn-outline-success exclusive-reply-btn"
                                    onclick="showItemExclusiveReplyModal('${item.item_id}', event)"
                                    title="设置专属回复语">
                                <i class="bi bi-chat-heart"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-primary copy-item-keywords-btn"
                                    onclick="copyItemKeywords('${item.item_id}', event)"
                                    title="复制回复到其他商品">
                                <i class="bi bi-clipboard-plus"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-danger delete-item-keywords-btn"
                                    onclick="deleteItemKeywords('${item.item_id}', event)"
                                    title="删除商品ID全部回复">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </div>
                    <div class="item-id-keywords">
                        ${keywordTags}
                    </div>
                    ${libraryTags}
                `;
                
                // 添加点击事件：筛选显示该商品的关键词
                cardElement.addEventListener('click', (e) => {
                    // 如果点击的是按钮，不执行筛选
                    if (e.target.closest('.delete-item-keywords-btn') ||
                        e.target.closest('.copy-item-keywords-btn') ||
                        e.target.closest('.exclusive-reply-btn')) {
                        return;
                    }
                    
                    // 管理员可以执行筛选功能
                    filterKeywordsByItemId(item.item_id);
                    // 更新卡片激活状态
                    updateItemIdCardActiveState(item.item_id);
                });
                
                console.log(`将管理员商品卡片添加到DOM: ${item.item_id}`);
                itemIdsGrid.appendChild(cardElement);
            } catch (error) {
                console.error(`渲染管理员商品卡片时出错:`, error);
                console.error('商品数据:', item);
            }
        });
        
        console.log(`管理员商品列表渲染完成，最终DOM中有 ${itemIdsGrid.children.length} 个子元素`);
        
        // 更新商品数量显示
        const itemIdsCountElements = document.querySelectorAll('#itemIdsCount, [id="itemIdsCount"]');
        itemIdsCountElements.forEach(element => {
            if (element) {
                element.textContent = `${itemsSummary.length} 个商品`;
            }
        });
    }
    
    // 确保容器显示
    if (itemIdsContainer) {
        itemIdsContainer.style.display = 'block';
    }
}

// 加载指定页的关键词
async function loadKeywordsPage(page) {
    if (!currentCookieId) {
        console.warn('没有选中的账号，无法加载关键词');
        return;
    }

    try {
        // 参数验证
        if (page < 1) page = 1;
        
        const response = await fetch(`${apiBase}/keywords-paginated/${currentCookieId}?page=${page}&page_size=${keywordsPageSize}`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });

        if (response.ok) {
            const result = await response.json();
            if (result.success) {
                const data = result.data;
                console.log('分页获取关键词数据:', data);

                // 更新分页信息
                currentKeywordsPage = data.current_page;
                totalKeywordsCount = data.total_count;
                totalKeywordsPages = data.total_pages;

                // 更新关键词数据缓存（只缓存当前页）
                keywordsData[currentCookieId] = data.keywords;
                
                // 渲染关键词列表
                renderKeywordsList(data.keywords);
                
                // 更新分页控件
                updateKeywordsPagination();
            } else {
                showToast('获取关键词失败', 'danger');
            }
        } else {
            showToast('获取关键词失败', 'danger');
        }
    } catch (error) {
        console.error('加载关键词页面失败:', error);
        showToast('加载关键词失败', 'danger');
    }
}

// 防止重复渲染的标志
let isRenderingConfiguredItems = false;

// 渲染已配置商品列表（普通用户视图）
function renderConfiguredItemsList(configuredItems) {
    console.log('renderConfiguredItemsList 被调用，数据:', configuredItems);
    
    // 防止重复渲染
    if (isRenderingConfiguredItems) {
        console.log('正在渲染中，跳过重复调用');
        return;
    }
    
    isRenderingConfiguredItems = true;
    
    try {
        const itemIdsGrid = document.getElementById('itemIdsGrid');
        const itemIdsCount = document.getElementById('itemIdsCount');
        const itemIdsContainer = document.getElementById('itemIdsContainer');
        
        // 清空容器
        if (itemIdsGrid) {
            itemIdsGrid.innerHTML = '';
        }
    
        if (!configuredItems || configuredItems.length === 0) {
            itemIdsGrid.innerHTML = `
                <div class="text-center p-5 text-muted">
                    <i class="bi bi-box-seam fs-1 mb-3"></i>
                    <h5 class="mb-2">暂无已配置自动回复的商品</h5>
                    <p class="mb-0">当前账号还没有为任何商品配置自动回复</p>
                </div>
            `;
            // 更新商品数量显示（需要查找可能的多个itemIdsCount元素）
            const itemIdsCountElements = document.querySelectorAll('#itemIdsCount, [id="itemIdsCount"]');
            itemIdsCountElements.forEach(element => {
                if (element) {
                    element.textContent = '0 个商品';
                }
            });
        } else {
            // 容器已经在上面清空了
        
        // 为普通用户重新添加功能说明（因为清空操作会移除之前插入的说明）
        const hasManagePermission = hasAutoReplyManagePermission();
        if (!hasManagePermission) {
            const infoHtml = `
                <div class="alert alert-info user-features-info mb-3">
                    <i class="bi bi-info-circle me-2"></i>
                    <strong>可用功能：</strong>
                    <span class="badge bg-primary ms-2"><i class="bi bi-chat-square-text me-1"></i>设置专属回复</span>
                    <span class="badge bg-info ms-1"><i class="bi bi-files me-1"></i>复制回复</span>
                    <span class="badge bg-danger ms-1"><i class="bi bi-trash me-1"></i>删除回复</span>
                </div>
            `;
            itemIdsGrid.insertAdjacentHTML('afterbegin', infoHtml);
        }
        
        // 为每个商品创建卡片元素
        console.log(`开始渲染 ${configuredItems.length} 个商品卡片`);
        configuredItems.forEach((item, index) => {
            try {
                console.log(`渲染第 ${index + 1} 个商品: ${item.item_id}`);
                const cardElement = document.createElement('div');
                cardElement.className = 'item-id-card';
                cardElement.setAttribute('data-item-id', item.item_id);
            
            // 生成关键词标签（显示"已配置"状态）
            const keywordTags = `<span class="item-id-count">已配置自动回复</span>`;
            
            // 生成词库信息标签
            const libraryTags = item.libraries && item.libraries.length > 0 ? `
                <div class="item-id-libraries">
                    <small class="text-info">
                        <i class="bi bi-collection me-1"></i>
                        词库: ${item.libraries.map(lib => `<span class="badge bg-info">${escapeHtml(lib)}</span>`).join(' ')}
                    </small>
                </div>
            ` : '';
            
            cardElement.innerHTML = `
                <div class="item-id-header">
                    <div class="item-id-title">
                        <i class="bi bi-box"></i>
                        商品ID
                        <span class="item-id-value">${escapeHtml(item.item_id)}</span>
                    </div>
                    <div class="item-id-actions">
                        <button class="btn btn-sm btn-outline-success exclusive-reply-btn"
                                onclick="showItemExclusiveReplyModal('${item.item_id}', event)"
                                title="设置专属回复语">
                            <i class="bi bi-chat-heart"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-primary copy-item-keywords-btn"
                                onclick="copyItemKeywords('${item.item_id}', event)"
                                title="复制回复到其他商品">
                            <i class="bi bi-clipboard-plus"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger delete-item-keywords-btn"
                                onclick="deleteItemKeywords('${item.item_id}', event)"
                                title="删除商品ID全部回复">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                </div>
                <div class="item-id-keywords">
                    ${keywordTags}
                </div>
                ${libraryTags}
            `;
            
            // 添加点击事件：筛选显示该商品的关键词
            cardElement.addEventListener('click', (e) => {
                // 如果点击的是按钮，不执行筛选
                if (e.target.closest('.delete-item-keywords-btn') ||
                    e.target.closest('.copy-item-keywords-btn') ||
                    e.target.closest('.exclusive-reply-btn')) {
                    return;
                }
                
                // 检查用户权限，普通用户不执行筛选功能
                const hasManagePermission = hasAutoReplyManagePermission();
                if (hasManagePermission) {
                    filterKeywordsByItemId(item.item_id);
                    // 更新卡片激活状态
                    updateItemIdCardActiveState(item.item_id);
                }
                // 普通用户点击卡片时不显示任何信息
            });
            
                console.log(`将第 ${index + 1} 个商品卡片添加到DOM: ${item.item_id}`);
                itemIdsGrid.appendChild(cardElement);
                console.log(`DOM中现在有 ${itemIdsGrid.children.length} 个子元素`);
            } catch (error) {
                console.error(`渲染第 ${index + 1} 个商品卡片时出错:`, error);
                console.error('商品数据:', item);
            }
        });
        
        console.log(`渲染完成，最终DOM中有 ${itemIdsGrid.children.length} 个子元素`);
        
        // 添加延迟检查，看看DOM是否被其他地方修改
        setTimeout(() => {
            console.log(`渲染完成1秒后，DOM中有 ${itemIdsGrid.children.length} 个子元素`);
            if (itemIdsGrid.children.length !== configuredItems.length + (hasAutoReplyManagePermission() ? 0 : 1)) {
                console.error('DOM元素数量异常！可能被其他地方修改了');
                console.log('当前DOM内容:', itemIdsGrid.innerHTML);
            }
        }, 1000);
        
        // 更新商品数量显示（需要查找可能的多个itemIdsCount元素）
        const itemIdsCountElements = document.querySelectorAll('#itemIdsCount, [id="itemIdsCount"]');
        itemIdsCountElements.forEach(element => {
            if (element) {
                element.textContent = `${configuredItems.length} 个商品`;
            }
        });
    }
    
        // 确保容器显示
        if (itemIdsContainer) {
            itemIdsContainer.style.display = 'block';
        }
    } finally {
        isRenderingConfiguredItems = false;
    }
}

// 隐藏关键词管理相关的UI元素
function hideKeywordManagementUI() {
    // 更新标题为普通用户视图
    const titleElement = document.getElementById('keywordManagementTitle');
    if (titleElement) {
        titleElement.innerHTML = '<i class="bi bi-box-seam me-2"></i>已配置自动回复的商品';
    }
    
    // 隐藏添加关键词区域
    const keywordInputArea = document.querySelector('.keyword-input-area');
    if (keywordInputArea) {
        keywordInputArea.style.display = 'none';
    }
    
    // 隐藏搜索区域
    const keywordSearchArea = document.querySelector('.keyword-search-area');
    if (keywordSearchArea) {
        keywordSearchArea.style.display = 'none';
    }
    
    // 隐藏关键词列表
    const keywordsList = document.getElementById('keywordsList');
    if (keywordsList) {
        keywordsList.style.display = 'none';
    }
    
    // 隐藏分页控件
    const pagination = document.getElementById('keywordsPagination');
    if (pagination) {
        pagination.style.display = 'none';
    }
    
    // 隐藏关键词管理标题区域中的操作按钮
    const keywordHeader = document.querySelector('.keyword-header');
    if (keywordHeader) {
        const actionButtons = keywordHeader.querySelector('.btn-group');
        if (actionButtons) {
            actionButtons.style.display = 'none';
        }
    }
    
    // 隐藏商品ID容器的标题（避免重复显示）
    const itemIdsHeader = document.querySelector('.item-ids-header');
    if (itemIdsHeader) {
        itemIdsHeader.style.display = 'none';
    }
    
    // 确保已配置商品区域显示
    const itemIdsContainer = document.getElementById('itemIdsContainer');
    if (itemIdsContainer) {
        itemIdsContainer.style.display = 'block';
    }
}

// 显示用户权限提示信息
function showUserPermissionMessage(message) {
    const itemIdsGrid = document.getElementById('itemIdsGrid');
    const alertHtml = `
        <div class="alert alert-warning mb-3">
            <i class="bi bi-exclamation-triangle me-2"></i>
            ${escapeHtml(message || '您只能查看已配置自动回复的商品信息')}
        </div>
    `;
    if (itemIdsGrid) {
        itemIdsGrid.insertAdjacentHTML('afterbegin', alertHtml);
    }
}

// 根据权限更新关键词管理UI
function updateKeywordManagementUI(hasManagePermission) {
    
    // 更新标题
    const titleElement = document.getElementById('keywordManagementTitle');
    if (titleElement) {
        if (hasManagePermission) {
            titleElement.innerHTML = '<i class="bi bi-chat-dots me-2"></i>关键词管理';
        } else {
            titleElement.innerHTML = '<i class="bi bi-box-seam me-2"></i>已配置自动回复的商品';
        }
    }
    
    // 添加关键词区域
    const keywordInputArea = document.querySelector('.keyword-input-area');
    if (keywordInputArea) {
        keywordInputArea.style.display = hasManagePermission ? 'block' : 'none';
    }
    
    // 搜索区域
    const keywordSearchArea = document.querySelector('.keyword-search-area');
    if (keywordSearchArea) {
        keywordSearchArea.style.display = hasManagePermission ? 'block' : 'none';
    }
    
    // 关键词列表
    const keywordsList = document.getElementById('keywordsList');
    if (keywordsList) {
        keywordsList.style.display = hasManagePermission ? 'block' : 'none';
    }
    
    // 分页控件
    const pagination = document.getElementById('keywordsPagination');
    if (pagination) {
        pagination.style.display = hasManagePermission ? 'block' : 'none';
    }
    
    // 关键词管理标题区域中的操作按钮
    const keywordHeader = document.querySelector('.keyword-header');
    if (keywordHeader) {
        const actionButtons = keywordHeader.querySelector('.btn-group');
        if (actionButtons) {
            actionButtons.style.display = hasManagePermission ? 'flex' : 'none';
        }
        
        // 对于普通用户，隐藏整个header
        if (!hasManagePermission) {
            keywordHeader.style.display = 'none';
        } else {
            keywordHeader.style.display = 'flex';
        }
    }
    
    // 商品ID容器的标题
    const itemIdsHeader = document.querySelector('.item-ids-header');
    if (itemIdsHeader) {
        if (hasManagePermission) {
            // 管理员显示原有的标题
            itemIdsHeader.style.display = 'block';
            // 确保标题内容正确
            if (!itemIdsHeader.querySelector('h4')) {
                itemIdsHeader.innerHTML = `
                    <h4>
                        <i class="bi bi-box-seam me-2"></i>
                        已配置自动回复的商品
                    </h4>
                    <div class="item-ids-stats">
                        <span id="itemIdsCount" class="badge bg-primary">0 个商品</span>
                    </div>
                `;
            }
        } else {
            // 普通用户显示简化的标题
            itemIdsHeader.style.display = 'block';
            itemIdsHeader.innerHTML = `
                <div style="text-align: center; margin-bottom: 2rem;">
                    <h3 style="color: #495057; font-weight: 600;">
                        <i class="bi bi-box-seam me-2 text-primary"></i>
                        已配置自动回复的商品
                    </h3>
                    <p class="text-muted mb-3">查看和管理您已配置自动回复的商品</p>
                    <div class="item-ids-stats">
                        <span id="itemIdsCount" class="badge bg-primary fs-6 px-3 py-2">0 个商品</span>
                    </div>
                </div>
            `;
        }
    }
    
    // 确保已配置商品区域始终显示
    const itemIdsContainer = document.getElementById('itemIdsContainer');
    if (itemIdsContainer) {
        itemIdsContainer.style.display = 'block';
        
        // 为普通用户调整容器样式，使其更突出
        if (!hasManagePermission) {
            itemIdsContainer.style.marginTop = '0';
            itemIdsContainer.style.background = '#f8f9fa';
            itemIdsContainer.style.borderRadius = '12px';
            itemIdsContainer.style.padding = '2rem';
            itemIdsContainer.style.border = '1px solid #e9ecef';
        } else {
            // 重置管理员样式
            itemIdsContainer.style.marginTop = '';
            itemIdsContainer.style.background = '';
            itemIdsContainer.style.borderRadius = '';
            itemIdsContainer.style.padding = '';
            itemIdsContainer.style.border = '';
        }
    }
    
    // 注意：功能说明现在在 renderConfiguredItemsList 函数中处理，避免重复插入
}

// 根据权限获取关键词操作按钮
function getKeywordActionButtons(index, isImageType) {
    const hasManagePermission = (currentUserInfo && currentUserInfo.is_admin) || 
                               (currentUserPermissions && currentUserPermissions.includes('auto_reply_manage'));
    
    if (!hasManagePermission) {
        // 普通用户不显示任何操作按钮
        return '';
    }
    
    // 管理员显示完整的操作按钮
    return `
        <button class="action-btn edit-btn ${isImageType ? 'edit-btn-disabled' : ''}" onclick="${isImageType ? 'editImageKeyword' : 'editKeyword'}(${index})" title="${isImageType ? '图片关键词不支持编辑' : '编辑'}">
            <i class="bi bi-pencil"></i>
        </button>
        <button class="action-btn delete-btn" onclick="deleteKeyword('${currentCookieId}', ${index})" title="删除">
            <i class="bi bi-trash"></i>
        </button>
    `;
}

// 更新分页控件
function updateKeywordsPagination() {
    const paginationContainer = document.getElementById('keywordsPagination');
    const prevPageItem = document.getElementById('prevPageItem');
    const nextPageItem = document.getElementById('nextPageItem');
    const currentPageText = document.getElementById('currentPageText');
    const paginationInfo = document.getElementById('keywordsPaginationInfo');

    if (!paginationContainer) return;

    // 如果总数为0或只有一页，隐藏分页控件
    if (totalKeywordsCount === 0 || totalKeywordsPages <= 1) {
        paginationContainer.style.display = 'none';
        return;
    }

    // 显示分页控件
    paginationContainer.style.display = 'block';

    // 更新页码显示
    currentPageText.textContent = currentKeywordsPage;

    // 更新上一页按钮状态
    if (currentKeywordsPage <= 1) {
        prevPageItem.classList.add('disabled');
    } else {
        prevPageItem.classList.remove('disabled');
    }

    // 更新下一页按钮状态
    if (currentKeywordsPage >= totalKeywordsPages) {
        nextPageItem.classList.add('disabled');
    } else {
        nextPageItem.classList.remove('disabled');
    }

    // 更新分页信息
    const startItem = (currentKeywordsPage - 1) * keywordsPageSize + 1;
    const endItem = Math.min(currentKeywordsPage * keywordsPageSize, totalKeywordsCount);
    paginationInfo.textContent = `显示第 ${startItem}-${endItem} 项，共 ${totalKeywordsCount} 项关键词（第 ${currentKeywordsPage}/${totalKeywordsPages} 页）`;
}

// 更新账号徽章显示
function updateAccountBadge(accountId, isEnabled) {
    const badge = document.getElementById('currentAccountBadge');
    if (!badge) return;

    const statusIcon = isEnabled ? '🟢' : '🔴';
    const statusText = isEnabled ? '启用' : '禁用';
    const statusClass = isEnabled ? 'bg-success' : 'bg-warning';

    badge.innerHTML = `
    <span class="badge ${statusClass} me-2">
        ${statusIcon} ${accountId}
    </span>
    <small class="text-muted">
        状态: ${statusText}
        ${!isEnabled ? ' (配置的关键词不会参与自动回复)' : ''}
    </small>
    `;
}

// 显示添加关键词表单
function showAddKeywordForm() {
    // 检查用户权限（管理员或有auto_reply_manage权限）
    const hasManagePermission = (currentUserInfo && currentUserInfo.is_admin) || 
                               (currentUserPermissions && currentUserPermissions.includes('auto_reply_manage'));

    if (!hasManagePermission) {
        showToast('您没有权限执行此操作', 'warning');
        return;
    }

    const form = document.getElementById('addKeywordForm');
    form.style.display = form.style.display === 'none' ? 'block' : 'none';

    if (form.style.display === 'block') {
        document.getElementById('newKeyword').focus();
    }
}

// 加载商品列表
async function loadItemsList(accountId) {
    try {
    const response = await fetch(`${apiBase}/items/${accountId}`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        const data = await response.json();
        const items = data.items || [];

        // 更新商品选择下拉框
        const selectElement = document.getElementById('newItemIdSelect');
        if (selectElement) {
        // 清空现有选项（保留第一个默认选项）
        selectElement.innerHTML = '<option value="">选择商品或留空表示通用关键词</option>';

        // 添加商品选项
        items.forEach(item => {
            const option = document.createElement('option');
            option.value = item.item_id;
            option.textContent = `${item.item_id} - ${item.item_title}`;
            selectElement.appendChild(option);
        });
        }

        console.log(`加载了 ${items.length} 个商品到选择列表`);
    } else {
        console.warn('加载商品列表失败:', response.status);
    }
    } catch (error) {
    console.error('加载商品列表时发生错误:', error);
    }
}



// 添加或更新关键词
async function addKeyword() {
    // 检查用户权限（管理员或有auto_reply_manage权限）
    const hasManagePermission = (currentUserInfo && currentUserInfo.is_admin) || 
                               (currentUserPermissions && currentUserPermissions.includes('auto_reply_manage'));
    
    if (!hasManagePermission) {
        showToast('您没有权限管理关键词', 'warning');
        return;
    }

    const keyword = document.getElementById('newKeyword').value.trim();
    const reply = document.getElementById('newReply').value.trim();
    const itemId = document.getElementById('newItemIdSelect').value.trim();

    if (!keyword || !reply) {
    showToast('请填写关键词和回复内容', 'warning');
    return;
    }

    if (!currentCookieId) {
    showToast('请先选择账号', 'warning');
    return;
    }

    // 检查是否为编辑模式
    const isEditMode = typeof window.editingIndex !== 'undefined';
    const actionText = isEditMode ? '更新' : '添加';

    try {
    toggleLoading(true);

    // 获取当前关键词列表
    let currentKeywords = [...(keywordsData[currentCookieId] || [])];

    // 如果是编辑模式，先移除原关键词
    if (isEditMode) {
        currentKeywords.splice(window.editingIndex, 1);
    }

    // 准备要保存的关键词列表（只包含文本类型的关键字）
    let textKeywords = currentKeywords.filter(item => (item.type || 'text') === 'text');

    // 如果是编辑模式，先移除原关键词
    if (isEditMode && typeof window.editingIndex !== 'undefined') {
        // 需要重新计算在文本关键字中的索引
        const originalKeyword = keywordsData[currentCookieId][window.editingIndex];
        const textIndex = textKeywords.findIndex(item =>
            item.keyword === originalKeyword.keyword &&
            (item.item_id || '') === (originalKeyword.item_id || '')
        );
        if (textIndex !== -1) {
            textKeywords.splice(textIndex, 1);
        }
    }

    // 检查关键词是否已存在（考虑商品ID，检查所有类型的关键词）
    const allKeywords = keywordsData[currentCookieId] || [];
    const existingKeyword = allKeywords.find(item =>
        item.keyword === keyword &&
        (item.item_id || '') === (itemId || '')
    );
    if (existingKeyword) {
        const itemIdText = itemId ? `（商品ID: ${itemId}）` : '（通用关键词）';
        const typeText = existingKeyword.type === 'image' ? '图片' : '文本';
        showToast(`关键词 "${keyword}" ${itemIdText} 已存在（${typeText}关键词），请使用其他关键词或商品ID`, 'warning');
        toggleLoading(false);
        return;
    }

    // 添加新关键词或更新的关键词
    const newKeyword = {
        keyword: keyword,
        reply: reply,
        item_id: itemId || ''
    };
    textKeywords.push(newKeyword);

    const response = await fetch(`${apiBase}/keywords-with-item-id/${currentCookieId}`, {
        method: 'POST',
        headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify({
        keywords: textKeywords
        })
    });

    if (response.ok) {
        showToast(`✨ 关键词 "${keyword}" ${actionText}成功！`, 'success');

        // 清空输入框并重置样式
        const keywordInput = document.getElementById('newKeyword');
        const replyInput = document.getElementById('newReply');
        const selectElement = document.getElementById('newItemIdSelect');
        const addBtn = document.querySelector('.add-btn');

        keywordInput.value = '';
        replyInput.value = '';
        if (selectElement) {
        selectElement.value = '';
        }
        keywordInput.style.borderColor = '#e5e7eb';
        replyInput.style.borderColor = '#e5e7eb';
        addBtn.style.opacity = '0.7';
        addBtn.style.transform = 'scale(0.95)';

        // 如果是编辑模式，重置编辑状态
        if (isEditMode) {
        delete window.editingIndex;
        delete window.originalKeyword;

        // 恢复添加按钮
        addBtn.innerHTML = '<i class="bi bi-plus-lg"></i>添加';
        addBtn.style.background = 'linear-gradient(135deg, #10b981 0%, #059669 100%)';

        // 移除取消按钮
        const cancelBtn = document.getElementById('cancelEditBtn');
        if (cancelBtn) {
            cancelBtn.remove();
        }
        }

        // 聚焦到关键词输入框，方便连续添加
        setTimeout(() => {
        keywordInput.focus();
        }, 100);

        // 只刷新关键词列表，不重新加载整个界面
        await refreshKeywordsList();
    } else {
        try {
            const errorData = await response.json();
            const errorMessage = errorData.detail || '关键词添加失败';
            console.error('关键词添加失败:', errorMessage);

            // 检查是否是重复关键词的错误
            if (errorMessage.includes('关键词已存在') || errorMessage.includes('关键词重复') || errorMessage.includes('UNIQUE constraint')) {
                showToast(`❌ 关键词重复：${errorMessage}`, 'warning');
            } else {
                showToast(`❌ ${errorMessage}`, 'danger');
            }
        } catch (parseError) {
            // 如果无法解析JSON，使用原始文本
            const errorText = await response.text();
            console.error('关键词添加失败:', errorText);
            showToast('❌ 关键词添加失败', 'danger');
        }
    }
    } catch (error) {
    console.error('添加关键词失败:', error);
    showToast('添加关键词失败', 'danger');
    } finally {
    toggleLoading(false);
    }
}

// 渲染现代化关键词列表
function renderKeywordsList(keywords) {
    console.log('渲染关键词列表:', keywords); // 调试信息
    const container = document.getElementById('keywordsList');

    if (!container) {
    console.error('找不到关键词列表容器元素');
    return;
    }

    container.innerHTML = '';

    if (!keywords || keywords.length === 0) {
    console.log('关键词列表为空，显示空状态');
    container.innerHTML = `
        <div class="empty-state">
        <i class="bi bi-chat-dots"></i>
        <h3>还没有关键词</h3>
        <p>添加第一个关键词，让您的闲鱼店铺自动回复客户消息</p>
        <button class="quick-add-btn" onclick="focusKeywordInput()">
            <i class="bi bi-plus-lg me-2"></i>立即添加
        </button>
        </div>
    `;
    // 即使关键词为空，也要渲染商品ID列表（显示空状态）
    renderItemIdsList(keywords || []);
    return;
    }

    console.log(`开始渲染 ${keywords.length} 个关键词`);

    keywords.forEach((item, index) => {
    console.log(`渲染关键词 ${index + 1}:`, item); // 调试信息

    const keywordItem = document.createElement('div');
    keywordItem.className = 'keyword-item';

    // 判断关键词类型
    const keywordType = item.type || 'text'; // 默认为文本类型
    const isImageType = keywordType === 'image';

    // 类型标识
    const typeBadge = isImageType ?
        '<span class="keyword-type-badge keyword-type-image"><i class="bi bi-image"></i> 图片</span>' :
        '<span class="keyword-type-badge keyword-type-text"><i class="bi bi-chat-text"></i> 文本</span>';

    // 商品ID显示
    const itemIdDisplay = item.item_id ?
        `<small class="text-muted d-block"><i class="bi bi-box"></i> 商品ID: ${item.item_id}</small>` :
        '<small class="text-muted d-block"><i class="bi bi-globe"></i> 通用关键词</small>';

    // 内容显示
    let contentDisplay = '';
    if (isImageType) {
        // 图片类型显示图片预览
        const imageUrl = item.reply || item.image_url || '';
        contentDisplay = imageUrl ?
            `<div class="d-flex align-items-center gap-3">
                <img src="${imageUrl}" alt="关键词图片" class="keyword-image-preview" onclick="showImageModal('${imageUrl}')">
                <div class="flex-grow-1">
                    <p class="reply-text mb-0">用户发送关键词时将回复此图片</p>
                    <small class="text-muted">点击图片查看大图</small>
                </div>
            </div>` :
            '<p class="reply-text text-muted">图片加载失败</p>';
    } else {
        // 文本类型显示文本内容
        contentDisplay = `<p class="reply-text">${item.reply || ''}</p>`;
    }

    keywordItem.innerHTML = `
        <div class="keyword-item-header">
        <div class="keyword-tag">
            <i class="bi bi-tag-fill"></i>
            ${item.keyword}
            ${typeBadge}
            ${itemIdDisplay}
        </div>
        <div class="keyword-actions">
            ${getKeywordActionButtons(index, isImageType)}
        </div>
        </div>
        <div class="keyword-content">
        ${contentDisplay}
        </div>
    `;
    container.appendChild(keywordItem);
    });

    console.log('关键词列表渲染完成');
    
    // 渲染关键词后，同时渲染商品ID列表
    renderItemIdsList(keywords);
}

// 渲染商品ID列表
function renderItemIdsList(keywords) {
    console.log('开始渲染商品ID列表，关键词数量:', keywords.length);
    
    const container = document.getElementById('itemIdsContainer');
    const grid = document.getElementById('itemIdsGrid');
    const countBadge = document.getElementById('itemIdsCount');
    
    if (!container || !grid || !countBadge) {
        console.warn('商品ID容器元素未找到');
        return;
    }
    
    // 提取有商品ID的关键词并按商品ID分组
    const itemIdGroups = extractItemIdGroups(keywords);
    const itemIds = Object.keys(itemIdGroups);
    
    console.log('提取到的商品ID分组:', itemIdGroups);
    console.log('商品ID列表:', itemIds);
    
    // 更新计数
    countBadge.textContent = `${itemIds.length} 个商品`;
    
    // 清空网格
    grid.innerHTML = '';
    
    if (itemIds.length === 0) {
        console.log('没有找到有商品ID的关键词');
        // 显示空状态
        grid.innerHTML = `
            <div class="item-ids-empty col-12">
                <i class="bi bi-box-seam"></i>
                <h5>暂无设置商品关键词</h5>
                <p>添加关键词时选择特定商品ID，该商品将显示在此处</p>
            </div>
        `;
        container.style.display = 'block';
        return;
    }
    
    // 显示容器
    container.style.display = 'block';
    
    // 渲染每个商品ID的卡片
    itemIds.forEach(itemId => {
        const keywordsForItem = itemIdGroups[itemId];
        console.log(`正在为商品ID ${itemId} 创建卡片，关键词数量: ${keywordsForItem.length}`);
        const card = createItemIdCard(itemId, keywordsForItem);
        grid.appendChild(card);
    });
    
    console.log(`商品ID列表渲染完成，共 ${itemIds.length} 个商品`);
}

// 从关键词数据中提取商品ID分组
function extractItemIdGroups(keywords) {
    const groups = {};
    
    keywords.forEach(keyword => {
        const itemId = keyword.item_id;
        if (itemId && itemId.trim()) {
            if (!groups[itemId]) {
                groups[itemId] = [];
            }
            groups[itemId].push(keyword);
        }
    });
    
    return groups;
}

// 创建商品ID卡片
function createItemIdCard(itemId, keywords) {
    const card = document.createElement('div');
    card.className = 'item-id-card';
    card.setAttribute('data-item-id', itemId);
    
    // 统计不同类型的关键词
    const textKeywords = keywords.filter(k => (k.type || 'text') === 'text');
    const imageKeywords = keywords.filter(k => k.type === 'image');
    
    // 收集词库信息
    const libraries = new Set();
    keywords.forEach(keyword => {
        if (keyword.library_name) {
            libraries.add(keyword.library_name);
        }
    });
    const libraryNames = Array.from(libraries);
    
    // 生成关键词标签
    const keywordTags = keywords.slice(0, 6).map(keyword => {
        const type = (keyword.type || 'text') === 'image' ? 'image-type' : 'text-type';
        const displayText = keyword.keyword.length > 8 ? keyword.keyword.substring(0, 8) + '...' : keyword.keyword;
        return `<span class="item-id-keyword ${type}" title="${keyword.keyword}">${displayText}</span>`;
    }).join('');
    
    const moreCount = keywords.length > 6 ? keywords.length - 6 : 0;
    const moreTag = moreCount > 0 ? `<span class="item-id-keyword">+${moreCount}</span>` : '';
    
    // 生成词库信息标签
    const libraryTags = libraryNames.length > 0 ? `
        <div class="item-id-libraries">
            <small class="text-info">
                <i class="bi bi-collection me-1"></i>
                词库: ${libraryNames.map(lib => `<span class="badge bg-info">${escapeHtml(lib)}</span>`).join(' ')}
            </small>
        </div>
    ` : '';
    
    card.innerHTML = `
        <div class="item-id-header">
            <div class="item-id-title">
                <i class="bi bi-box"></i>
                商品ID
                <span class="item-id-value">${itemId}</span>
            </div>
            <div class="item-id-actions">
                <button class="btn btn-sm btn-outline-success exclusive-reply-btn"
                        onclick="showItemExclusiveReplyModal('${itemId}', event)"
                        title="设置专属回复语">
                    <i class="bi bi-chat-heart"></i>
                </button>
                <button class="btn btn-sm btn-outline-primary copy-item-keywords-btn"
                        onclick="copyItemKeywords('${itemId}', event)"
                        title="复制回复到其他商品">
                    <i class="bi bi-clipboard-plus"></i>
                </button>
                <button class="btn btn-sm btn-outline-danger delete-item-keywords-btn"
                        onclick="deleteItemKeywords('${itemId}', event)"
                        title="删除商品ID全部回复">
                    <i class="bi bi-trash"></i>
                </button>
            </div>
        </div>
        <div class="item-id-keywords">
            ${keywordTags}
            ${moreTag}
        </div>
        ${libraryTags}
    `;
    
    console.log(`创建商品ID卡片: ${itemId}, 关键词数量: ${keywords.length}`);
    console.log('卡片HTML内容:', card.innerHTML);
    
    // 验证删除按钮是否存在
    setTimeout(() => {
        const deleteBtn = card.querySelector('.delete-item-keywords-btn');
        console.log(`商品ID ${itemId} 的删除按钮:`, deleteBtn);
        if (deleteBtn) {
            console.log('删除按钮样式:', window.getComputedStyle(deleteBtn));
        }
    }, 100);
    
    // 添加点击事件：筛选显示该商品的关键词
    card.addEventListener('click', (e) => {
        // 如果点击的是删除按钮、复制按钮或专属回复语按钮，不执行筛选
        if (e.target.closest('.delete-item-keywords-btn') ||
            e.target.closest('.copy-item-keywords-btn') ||
            e.target.closest('.exclusive-reply-btn')) {
            return;
        }
        
        // 检查用户权限，普通用户不执行筛选功能
        const hasManagePermission = hasAutoReplyManagePermission();
        if (hasManagePermission) {
            filterKeywordsByItemId(itemId);
            // 更新卡片激活状态
            updateItemIdCardActiveState(itemId);
        }
        // 普通用户点击卡片时不显示任何信息
    });
    
    return card;
}

// 按商品ID筛选关键词
function filterKeywordsByItemId(itemId) {
    if (!currentCookieId || !keywordsData[currentCookieId]) {
        return;
    }
    
    const allKeywords = keywordsData[currentCookieId];
    const filteredKeywords = allKeywords.filter(keyword => keyword.item_id === itemId);
    
    // 更新搜索状态
    isSearching = true;
    currentSearchTerm = `商品ID: ${itemId}`;
    
    if (!originalKeywordsList.length) {
        originalKeywordsList = [...allKeywords];
    }
    
    // 渲染筛选后的关键词
    renderKeywordsList(filteredKeywords);
    
    // 显示搜索结果信息
    const searchResultsInfo = document.getElementById('searchResultsInfo');
    const searchResultsText = document.getElementById('searchResultsText');
    const searchInput = document.getElementById('searchKeyword');
    
    if (searchResultsInfo && searchResultsText) {
        searchResultsInfo.style.display = 'block';
        searchResultsText.textContent = `正在显示商品 "${itemId}" 的 ${filteredKeywords.length} 个关键词`;
    }
    
    if (searchInput) {
        searchInput.value = itemId;
        searchInput.style.borderColor = '#f59e0b';
        searchInput.style.backgroundColor = '#fffbeb';
    }
    
    // 滚动到关键词列表顶部
    const keywordsList = document.getElementById('keywordsList');
    if (keywordsList) {
        keywordsList.scrollIntoView({ behavior: 'smooth' });
    }
    
    showToast(`正在显示商品 "${itemId}" 的关键词`, 'success');
}

// 更新商品ID卡片的激活状态
function updateItemIdCardActiveState(activeItemId) {
    const cards = document.querySelectorAll('.item-id-card');
    cards.forEach(card => {
        const itemId = card.getAttribute('data-item-id');
        if (itemId === activeItemId) {
            card.classList.add('active');
        } else {
            card.classList.remove('active');
        }
    });
}

// 聚焦到关键词输入框
function focusKeywordInput() {
    document.getElementById('newKeyword').focus();
}

// 编辑关键词 - 改进版本
function editKeyword(index) {
    // 检查用户权限（管理员或有auto_reply_manage权限）
    const hasManagePermission = (currentUserInfo && currentUserInfo.is_admin) || 
                               (currentUserPermissions && currentUserPermissions.includes('auto_reply_manage'));
    
    if (!hasManagePermission) {
        showToast('您没有权限执行此操作', 'warning');
        return;
    }

    const keywords = keywordsData[currentCookieId] || [];
    const keyword = keywords[index];

    if (!keyword) {
        showToast('关键词不存在', 'warning');
        return;
    }

    // 将关键词信息填入输入框
    document.getElementById('newKeyword').value = keyword.keyword;
    document.getElementById('newReply').value = keyword.reply;

    // 设置商品ID选择框
    const selectElement = document.getElementById('newItemIdSelect');
    if (selectElement) {
        selectElement.value = keyword.item_id || '';
    }

    // 设置编辑模式标识
    window.editingIndex = index;
    window.originalKeyword = keyword.keyword;
    window.originalItemId = keyword.item_id || '';

    // 更新按钮文本和样式
    const addBtn = document.querySelector('.add-btn');
    addBtn.innerHTML = '<i class="bi bi-check-lg"></i>更新';
    addBtn.style.background = 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)';

    // 显示取消按钮
    showCancelEditButton();

    // 聚焦到关键词输入框并选中文本
    setTimeout(() => {
        const keywordInput = document.getElementById('newKeyword');
        keywordInput.focus();
        keywordInput.select();
    }, 100);

    showToast('📝 编辑模式：修改后点击"更新"按钮保存', 'info');
}

// 显示取消编辑按钮
function showCancelEditButton() {
    // 检查是否已存在取消按钮
    if (document.getElementById('cancelEditBtn')) {
        return;
    }

    const addBtn = document.querySelector('.add-btn');
    const cancelBtn = document.createElement('button');
    cancelBtn.id = 'cancelEditBtn';
    cancelBtn.className = 'btn btn-outline-secondary';
    cancelBtn.style.marginLeft = '0.5rem';
    cancelBtn.innerHTML = '<i class="bi bi-x-lg"></i>取消';
    cancelBtn.onclick = cancelEdit;

    addBtn.parentNode.appendChild(cancelBtn);
}

// 取消编辑
function cancelEdit() {
    // 清空输入框
    document.getElementById('newKeyword').value = '';
    document.getElementById('newReply').value = '';

    // 清空商品ID选择框
    const selectElement = document.getElementById('newItemIdSelect');
    if (selectElement) {
        selectElement.value = '';
    }

    // 重置编辑状态
    delete window.editingIndex;
    delete window.originalKeyword;
    delete window.originalItemId;

    // 恢复添加按钮
    const addBtn = document.querySelector('.add-btn');
    addBtn.innerHTML = '<i class="bi bi-plus-lg"></i>添加';
    addBtn.style.background = 'linear-gradient(135deg, #10b981 0%, #059669 100%)';

    // 移除取消按钮
    const cancelBtn = document.getElementById('cancelEditBtn');
    if (cancelBtn) {
        cancelBtn.remove();
    }

    showToast('已取消编辑', 'info');
}

// 删除关键词
async function deleteKeyword(cookieId, index) {
    // 检查用户权限（管理员或有auto_reply_manage权限）
    const hasManagePermission = (currentUserInfo && currentUserInfo.is_admin) || 
                               (currentUserPermissions && currentUserPermissions.includes('auto_reply_manage'));
    
    if (!hasManagePermission) {
        showToast('您没有权限执行此操作', 'warning');
        return;
    }

    if (!confirm('确定要删除这个关键词吗？')) {
        return;
    }

    try {
        toggleLoading(true);

        // 使用新的删除API
        const response = await fetch(`${apiBase}/keywords/${cookieId}/${index}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });

        if (response.ok) {
            showToast('关键词删除成功', 'success');
            // 只刷新关键词列表，不重新加载整个界面
            await refreshKeywordsList();
        } else {
            const errorText = await response.text();
            console.error('关键词删除失败:', errorText);
            showToast('关键词删除失败', 'danger');
        }
    } catch (error) {
        console.error('删除关键词失败:', error);
        showToast('删除关键词删除失败', 'danger');
    } finally {
        toggleLoading(false);
    }
}

// 测试删除API连接
async function testDeleteAPI() {
    console.log('测试删除API连接...');
    if (!currentCookieId) {
        alert('请先选择一个账号');
        return;
    }
    alert(`当前账号ID: ${currentCookieId}\nAPI基地址: ${apiBase}\n认证令牌: ${authToken ? '已设置' : '未设置'}`);
}

// 删除商品ID的所有关键词
async function deleteItemKeywords(itemId, event) {
    // 阻止事件冒泡，防止触发卡片的点击事件
    if (event) {
        event.stopPropagation();
    }
    
    // 检查当前是否有选中的cookie
    if (!currentCookieId) {
        showToast('请先选择一个账号', 'warning');
        return;
    }
    
    // 获取商品的关键词数量用于确认
    const keywords = keywordsData[currentCookieId] || [];
    const itemKeywords = keywords.filter(k => k.item_id === itemId);
    const keywordCount = itemKeywords.length;
    
    if (keywordCount === 0) {
        showToast('该商品没有配置关键词', 'info');
        return;
    }
    
    // 显示确认对话框
    const confirmMessage = `确定要删除商品ID "${itemId}" 的自动回复吗？\n\n此操作无法撤销！`;
    
    if (!confirm(confirmMessage)) {
        return;
    }
    
    try {
        toggleLoading(true);
        
        // 调用删除API
        const response = await fetch(`${apiBase}/keywords/${currentCookieId}/item/${itemId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'application/json'
            }
        });
        
        if (response.ok) {
            const result = await response.json();
            showToast(result.msg || '商品关键词删除成功', 'success');
            // 刷新关键词列表
            await refreshKeywordsList();
        } else {
            const errorText = await response.text();
            console.error('商品关键词删除失败:', errorText);
            
            let errorMsg = '商品关键词删除失败';
            try {
                const errorJson = JSON.parse(errorText);
                errorMsg = errorJson.detail || errorMsg;
            } catch (e) {
                // 解析失败，使用默认错误消息
            }
            
            showToast(errorMsg, 'danger');
        }
    } catch (error) {
        console.error('删除商品关键词时发生错误:', error);
        showToast('删除商品关键词失败', 'danger');
    } finally {
        toggleLoading(false);
    }
}

// 复制商品ID的所有关键词
async function copyItemKeywords(sourceItemId, event) {
    // 阻止事件冒泡，防止触发卡片的点击事件
    if (event) {
        event.stopPropagation();
    }
    
    // 检查当前是否有选中的cookie
    if (!currentCookieId) {
        showToast('请先选择一个账号', 'warning');
        return;
    }
    
    // 获取商品的关键词数量用于确认
    const keywords = keywordsData[currentCookieId] || [];
    const itemKeywords = keywords.filter(k => k.item_id === sourceItemId);
    const keywordCount = itemKeywords.length;
    
    if (keywordCount === 0) {
        showToast('该商品没有配置关键词', 'info');
        return;
    }
    
    // 弹出输入框让用户填写目标商品ID
    const targetItemId = prompt(`请输入要复制关键词的目标商品ID：\n\n当前商品ID: ${sourceItemId}\n目标商品ID:`);
    
    if (!targetItemId || !targetItemId.trim()) {
        return; // 用户取消或输入为空
    }

    const trimmedTargetItemId = targetItemId.trim();
    
    // 验证目标商品ID格式
    if (!/^\d+$/.test(trimmedTargetItemId)) {
        showToast('商品ID只能包含数字', 'warning');
        return;
    }

    // 检查目标商品是否已有关键词
    const targetKeywords = keywords.filter(k => k.item_id === trimmedTargetItemId);
    if (targetKeywords.length > 0) {
        showToast(`目标商品ID "${trimmedTargetItemId}" 已有关键词，请先删除或清空`, 'warning');
        return;
    }

    // 显示确认对话框
    const confirmMessage = `确定要将商品ID "${sourceItemId}" 的所有关键词复制到商品ID "${trimmedTargetItemId}" 吗？\n\n这将复制 ${keywordCount} 个关键词，包括：\n${itemKeywords.slice(0, 5).map(k => `• ${k.keyword}`).join('\n')}${keywordCount > 5 ? '\n• ...' : ''}`;
    
    if (!confirm(confirmMessage)) {
        return;
    }

    try {
        toggleLoading(true);

        const response = await fetch(`${apiBase}/keywords/${currentCookieId}/copy`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${authToken}`
            },
            body: JSON.stringify({
                source_item_id: sourceItemId,
                target_item_id: trimmedTargetItemId
            })
        });

        if (response.ok) {
            const result = await response.json();
            showToast(`${result.msg}，共复制了 ${result.copied_count} 个关键词`, 'success');
            
            // 刷新关键词列表
            await refreshKeywordsList();
        } else {
            const errorText = await response.text();
            console.error('复制商品关键词失败:', errorText);
            
            let errorMsg = '复制商品关键词失败';
            try {
                const errorJson = JSON.parse(errorText);
                errorMsg = errorJson.detail || errorMsg;
            } catch (e) {
                // 解析失败，使用默认错误消息
            }
            
            showToast(errorMsg, 'danger');
        }
    } catch (error) {
        console.error('复制商品关键词时发生错误:', error);
        showToast('复制商品关键词失败', 'danger');
    } finally {
        toggleLoading(false);
    }
}

// ================================
// 搜索功能
// ================================

// 全局变量存储搜索状态
let isSearching = false;
let currentSearchTerm = '';
let originalKeywordsList = [];

// 搜索关键词
async function searchKeywords() {
    // 检查用户权限（管理员或有auto_reply_manage权限）
    const hasManagePermission = (currentUserInfo && currentUserInfo.is_admin) || 
                               (currentUserPermissions && currentUserPermissions.includes('auto_reply_manage'));

    if (!hasManagePermission) {
        showToast('您没有权限执行此操作', 'warning');
        return;
    }

    const searchInput = document.getElementById('searchKeyword');
    const searchTerm = searchInput.value.trim().toLowerCase();
    
    if (!searchTerm) {
        showToast('请输入搜索内容', 'warning');
        return;
    }
    
    if (!currentCookieId) {
        showToast('请先选择账号', 'warning');
        return;
    }
    
    await performKeywordSearch(searchTerm);
}

// 执行关键词搜索
async function performKeywordSearch(searchTerm) {
    // 检查用户权限（管理员或有auto_reply_manage权限）
    const hasManagePermission = (currentUserInfo && currentUserInfo.is_admin) || 
                               (currentUserPermissions && currentUserPermissions.includes('auto_reply_manage'));

    if (!hasManagePermission) {
        console.warn('普通用户无权限执行关键词搜索');
        return;
    }

    const searchResultsInfo = document.getElementById('searchResultsInfo');
    const searchResultsText = document.getElementById('searchResultsText');
    const searchInput = document.getElementById('searchKeyword');
    
    try {
        // 暂时使用前端搜索（获取所有数据进行搜索）
        // TODO: 后续可以优化为后端搜索API
        const response = await fetch(`${apiBase}/keywords-with-item-id/${currentCookieId}`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });

        if (response.ok) {
            const allKeywords = await response.json();
            
            // 进行搜索过滤
            const filteredKeywords = allKeywords.filter(keyword => {
                const keywordMatch = keyword.keyword.toLowerCase().includes(searchTerm);
                const itemIdMatch = keyword.item_id && keyword.item_id.toLowerCase().includes(searchTerm);
                const replyMatch = keyword.reply && keyword.reply.toLowerCase().includes(searchTerm);
                return keywordMatch || itemIdMatch || replyMatch;
            });
            
            // 更新搜索状态
            isSearching = true;
            currentSearchTerm = searchTerm;
            originalKeywordsList = [...allKeywords];
            
            // 渲染搜索结果
            renderKeywordsList(filteredKeywords);
            
            // 隐藏分页控件（搜索结果不分页）
            const paginationContainer = document.getElementById('keywordsPagination');
            if (paginationContainer) {
                paginationContainer.style.display = 'none';
            }
            
            // 显示搜索结果信息
            if (searchResultsInfo) {
                searchResultsInfo.style.display = 'block';
            }
            if (searchResultsText) {
                searchResultsText.textContent = `找到 ${filteredKeywords.length} 个匹配 "${searchTerm}" 的关键词`;
            }
            
            // 改变搜索输入框样式
            if (searchInput) {
                searchInput.style.borderColor = '#667eea';
                searchInput.style.backgroundColor = '#f0f4ff';
            }
            
            console.log(`搜索 "${searchTerm}" 完成，找到 ${filteredKeywords.length} 个结果`);
        } else {
            showToast('搜索失败', 'danger');
        }
    } catch (error) {
        console.error('搜索关键词失败:', error);
        showToast('搜索失败', 'danger');
    }
}

// 清除搜索
// 重置搜索状态（不加载数据）
function resetSearchState() {
    const searchInput = document.getElementById('searchKeyword');
    const searchResultsInfo = document.getElementById('searchResultsInfo');
    
    // 清空搜索输入框
    if (searchInput) {
        searchInput.value = '';
        searchInput.style.borderColor = '#e5e7eb';
        searchInput.style.backgroundColor = 'white';
    }
    
    // 隐藏搜索结果信息
    if (searchResultsInfo) {
        searchResultsInfo.style.display = 'none';
    }
    
    // 重置搜索状态
    isSearching = false;
    currentSearchTerm = '';
    originalKeywordsList = [];
    
    // 清除商品ID卡片的激活状态
    const itemIdCards = document.querySelectorAll('.item-id-card');
    itemIdCards.forEach(card => {
        card.classList.remove('active');
    });
}

async function clearSearch() {
    // 检查用户权限（管理员或有auto_reply_manage权限）
    const hasManagePermission = (currentUserInfo && currentUserInfo.is_admin) || 
                               (currentUserPermissions && currentUserPermissions.includes('auto_reply_manage'));

    if (!hasManagePermission) {
        showToast('您没有权限执行此操作', 'warning');
        return;
    }

    const searchInput = document.getElementById('searchKeyword');
    const searchResultsInfo = document.getElementById('searchResultsInfo');
    
    // 清空搜索输入框
    if (searchInput) {
        searchInput.value = '';
        searchInput.style.borderColor = '#e5e7eb';
        searchInput.style.backgroundColor = 'white';
    }
    
    // 隐藏搜索结果信息
    if (searchResultsInfo) {
        searchResultsInfo.style.display = 'none';
    }
    
    // 重置搜索状态
    isSearching = false;
    currentSearchTerm = '';
    originalKeywordsList = [];
    
    // 恢复分页显示（仅管理员）
    if (currentCookieId) {
        const hasManagePermission = (currentUserInfo && currentUserInfo.is_admin) || 
                                   (currentUserPermissions && currentUserPermissions.includes('auto_reply_manage'));
        
        if (hasManagePermission) {
            await loadKeywordsPage(currentKeywordsPage);
        }
    }
    
    // 清除商品ID卡片的激活状态
    const itemIdCards = document.querySelectorAll('.item-id-card');
    itemIdCards.forEach(card => {
        card.classList.remove('active');
    });
    
    console.log('已清除搜索，恢复显示所有关键词');
}

// 显示/隐藏加载动画
function toggleLoading(show) {
    document.getElementById('loading').classList.toggle('d-none', !show);
}

// ================================
// 通用工具函数
// ================================

// 显示提示消息
function showToast(message, type = 'success') {
    const toastContainer = document.querySelector('.toast-container');
    const toast = document.createElement('div');
    toast.className = `toast align-items-center text-white bg-${type} border-0`;
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');
    toast.setAttribute('aria-atomic', 'true');

    toast.innerHTML = `
    <div class="d-flex">
        <div class="toast-body">
        ${message}
        </div>
        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    `;

    toastContainer.appendChild(toast);
    const bsToast = new bootstrap.Toast(toast, { delay: 3000 });
    bsToast.show();

    // 自动移除
    toast.addEventListener('hidden.bs.toast', () => {
    toast.remove();
    });
}

// 错误处理
async function handleApiError(err) {
    console.error(err);
    showToast(err.message || '操作失败', 'danger');
    toggleLoading(false);
}

// API请求包装
async function fetchJSON(url, opts = {}) {
    toggleLoading(true);
    try {
    // 添加认证头
    if (authToken) {
        opts.headers = opts.headers || {};
        opts.headers['Authorization'] = `Bearer ${authToken}`;
    }

    const res = await fetch(url, opts);
    if (res.status === 401) {
        // 未授权，跳转到登录页面
        localStorage.removeItem('auth_token');
        window.location.href = '/';
        return;
    }
    if (!res.ok) {
        let errorMessage = `HTTP ${res.status}`;
        try {
        const errorText = await res.text();
        if (errorText) {
            // 尝试解析JSON错误信息
            try {
            const errorJson = JSON.parse(errorText);
            errorMessage = errorJson.detail || errorJson.message || errorText;
            } catch {
            errorMessage = errorText;
            }
        }
        } catch {
        errorMessage = `HTTP ${res.status} ${res.statusText}`;
        }
        throw new Error(errorMessage);
    }
    const data = await res.json();
    toggleLoading(false);
    return data;
    } catch (err) {
    handleApiError(err);
    throw err;
    }
}

// ================================
// 【账号管理菜单】相关功能
// ================================

// 加载Cookie列表
async function loadCookies() {
    try {
    toggleLoading(true);
    const tbody = document.querySelector('#cookieTable tbody');
    tbody.innerHTML = '';

    // 使用优化的API获取账号列表（已包含关键词统计和所有设置信息）
    const accountsWithAllSettings = await fetchJSON(apiBase + '/cookies/details-with-settings');

    if (accountsWithAllSettings.length === 0) {
        tbody.innerHTML = `
        <tr>
            <td colspan="12" class="text-center py-4 text-muted empty-state">
            <i class="bi bi-inbox fs-1 d-block mb-3"></i>
            <h5>暂无账号</h5>
            <p class="mb-0">请添加新的闲鱼账号开始使用</p>
            </td>
        </tr>
        `;
        return;
    }

    // 数据已经包含所有设置信息，无需额外请求
    // 为了保持兼容性，确保数据格式正确
    accountsWithAllSettings.forEach(cookie => {
        cookie.keywordCount = cookie.keyword_count || 0;
        // 确保设置对象存在
        if (!cookie.defaultReply) {
            cookie.defaultReply = { enabled: false, reply_content: '', reply_once: false };
        }
        if (!cookie.aiReply) {
            cookie.aiReply = { ai_enabled: false, model_name: 'qwen-plus' };
        }
        if (cookie.pauseEnabled === undefined) {
            cookie.pauseEnabled = cookie.pause_enabled !== undefined ? cookie.pause_enabled : true;
        }
    });

    accountsWithAllSettings.forEach(cookie => {
        // 使用数据库中的实际状态，默认为启用
        const isEnabled = cookie.enabled === undefined ? true : cookie.enabled;

        console.log(`账号 ${cookie.id} 状态: enabled=${cookie.enabled}, isEnabled=${isEnabled}`); // 调试信息

        const tr = document.createElement('tr');
        tr.className = `account-row ${isEnabled ? 'enabled' : 'disabled'}`;
        // 默认回复状态标签
        const defaultReplyBadge = cookie.defaultReply.enabled ?
        '<span class="badge bg-success">启用</span>' :
        '<span class="badge bg-secondary">禁用</span>';

        // AI回复状态标签
        const aiReplyBadge = cookie.aiReply.ai_enabled ?
        '<span class="badge bg-primary">AI启用</span>' :
        '<span class="badge bg-secondary">AI禁用</span>';

        // 自动确认发货状态（默认开启）
        const autoConfirm = cookie.auto_confirm === undefined ? true : cookie.auto_confirm;
        
        // 暂停功能状态（默认开启）
        const pauseEnabled = cookie.pauseEnabled === undefined ? true : cookie.pauseEnabled;

        tr.innerHTML = `
        <td class="align-middle">
            <div class="cookie-id">
            <strong class="text-primary">${cookie.id}</strong>
            </div>
        </td>
        <td class="align-middle">
            <div class="cookie-value" title="点击复制Cookie" style="font-family: monospace; font-size: 0.875rem; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
            ${cookie.value || '未设置'}
            </div>
        </td>
        <td class="align-middle">
            <div class="d-flex align-items-center gap-2">
            <label class="status-toggle" title="${isEnabled ? '点击禁用' : '点击启用'}">
                <input type="checkbox" ${isEnabled ? 'checked' : ''} onchange="toggleAccountStatus('${cookie.id}', this.checked)">
                <span class="status-slider"></span>
            </label>
            <span class="status-badge ${isEnabled ? 'enabled' : 'disabled'}" title="${isEnabled ? '账号已启用' : '账号已禁用'}">
                <i class="bi bi-${isEnabled ? 'check-circle-fill' : 'x-circle-fill'}"></i>
            </span>
            </div>
        </td>
        <td class="align-middle">
            <div class="d-flex align-items-center gap-2">
                ${cookie.token_status === 'valid' ?
                    '<span class="badge bg-success" title="Token有效"><i class="bi bi-check-circle me-1"></i>有效</span>' :
                    '<span class="badge bg-danger" title="Token失效，请更新Cookie"><i class="bi bi-x-circle me-1"></i>失效</span>'
                }
                <button class="btn btn-sm btn-outline-secondary" onclick="refreshTokenStatus('${cookie.id}')" title="刷新Token状态">
                    <i class="bi bi-arrow-clockwise"></i>
                </button>
            </div>
        </td>
        <td class="align-middle">
            ${defaultReplyBadge}
        </td>
        <td class="align-middle">
            ${aiReplyBadge}
        </td>
        <td class="align-middle">
            <div class="d-flex align-items-center gap-2">
            <label class="status-toggle" title="${autoConfirm ? '点击关闭自动确认发货' : '点击开启自动确认发货'}">
                <input type="checkbox" ${autoConfirm ? 'checked' : ''} onchange="toggleAutoConfirm('${cookie.id}', this.checked)">
                <span class="status-slider"></span>
            </label>
            <span class="status-badge ${autoConfirm ? 'enabled' : 'disabled'}" title="${autoConfirm ? '自动确认发货已开启' : '自动确认发货已关闭'}">
                <i class="bi bi-${autoConfirm ? 'truck' : 'truck-flatbed'}"></i>
            </span>
            </div>
        </td>
        <td class="align-middle">
            <div class="remark-cell" data-cookie-id="${cookie.id}">
                <span class="remark-display" onclick="editRemark('${cookie.id}', '${(cookie.remark || '').replace(/'/g, '&#39;')}')" title="点击编辑备注" style="cursor: pointer; color: #6c757d; font-size: 0.875rem;">
                    ${cookie.remark || '<i class="bi bi-plus-circle text-muted"></i> 添加备注'}
                </span>
            </div>
        </td>
        <td class="align-middle">
            <div class="notification-wxid-cell" data-cookie-id="${cookie.id}">
                <span class="notification-wxid-display" onclick="editNotificationWxid('${cookie.id}', '${(cookie.notification_wxid || '').replace(/'/g, '&#39;')}')" title="点击编辑通知wxid" style="cursor: pointer; color: #6c757d; font-size: 0.875rem;">
                    ${cookie.notification_wxid ? '<i class="bi bi-wechat text-success me-1"></i>' + cookie.notification_wxid : '<i class="bi bi-plus-circle text-muted"></i> 设置wxid'}
                </span>
            </div>
        </td>
        <td class="align-middle">
            <div class="pause-duration-cell" data-cookie-id="${cookie.id}">
                <span class="pause-duration-display" onclick="editPauseDuration('${cookie.id}', ${cookie.pause_duration || 10})" title="点击编辑暂停时间" style="cursor: pointer; color: #6c757d; font-size: 0.875rem;">
                    <i class="bi bi-clock me-1"></i>${cookie.pause_duration || 10}分钟
                </span>
            </div>
        </td>
        <td class="align-middle">
            <div class="d-flex align-items-center gap-2">
            <label class="status-toggle" title="${pauseEnabled ? '点击关闭暂停功能' : '点击开启暂停功能'}">
                <input type="checkbox" ${pauseEnabled ? 'checked' : ''} onchange="togglePauseEnabled('${cookie.id}', this.checked)">
                <span class="status-slider"></span>
            </label>
            <span class="status-badge ${pauseEnabled ? 'enabled' : 'disabled'}" title="${pauseEnabled ? '暂停功能已启用' : '暂停功能已禁用'}">
                <i class="bi bi-${pauseEnabled ? 'pause-circle-fill' : 'play-circle-fill'}"></i>
            </span>
            </div>
        </td>
        <td class="align-middle">
            <div class="btn-group" role="group">
            <button class="btn btn-sm btn-outline-primary" onclick="editCookieInline('${cookie.id}', '${cookie.value}')" title="修改Cookie" ${!isEnabled ? 'disabled' : ''}>
                <i class="bi bi-pencil"></i>
            </button>
            <button class="btn btn-sm btn-outline-success" onclick="goToAutoReply('${cookie.id}')" title="${isEnabled ? '设置自动回复' : '配置关键词 (账号已禁用)'}">
                <i class="bi bi-arrow-right-circle"></i>
            </button>
            <button class="btn btn-sm btn-outline-warning" onclick="configAIReply('${cookie.id}')" title="配置AI回复" ${!isEnabled ? 'disabled' : ''}>
                <i class="bi bi-robot"></i>
            </button>
            <button class="btn btn-sm btn-outline-info" onclick="copyCookie('${cookie.id}', '${cookie.value}')" title="复制Cookie">
                <i class="bi bi-clipboard"></i>
            </button>
            <button class="btn btn-sm btn-outline-danger" onclick="delCookie('${cookie.id}')" title="删除账号">
                <i class="bi bi-trash"></i>
            </button>
            </div>
        </td>
        `;
        tbody.appendChild(tr);
    });

    // 为Cookie值添加点击复制功能
    document.querySelectorAll('.cookie-value').forEach(element => {
        element.style.cursor = 'pointer';
        element.addEventListener('click', function() {
        const cookieValue = this.textContent;
        if (cookieValue && cookieValue !== '未设置') {
            navigator.clipboard.writeText(cookieValue).then(() => {
            showToast('Cookie已复制到剪贴板', 'success');
            }).catch(() => {
            showToast('复制失败，请手动复制', 'error');
            });
        }
        });
    });

    // 重新初始化工具提示
    initTooltips();

    } catch (err) {
    // 错误已在fetchJSON中处理
    } finally {
    toggleLoading(false);
    }
}

// 复制Cookie
function copyCookie(id, value) {
    if (!value || value === '未设置') {
    showToast('该账号暂无Cookie值', 'warning');
    return;
    }

    navigator.clipboard.writeText(value).then(() => {
    showToast(`账号 "${id}" 的Cookie已复制到剪贴板`, 'success');
    }).catch(() => {
    // 降级方案：创建临时文本框
    const textArea = document.createElement('textarea');
    textArea.value = value;
    document.body.appendChild(textArea);
    textArea.select();
    try {
        document.execCommand('copy');
        showToast(`账号 "${id}" 的Cookie已复制到剪贴板`, 'success');
    } catch (err) {
        showToast('复制失败，请手动复制', 'error');
    }
    document.body.removeChild(textArea);
    });
}

// 通用复制到剪贴板函数
function copyToClipboard(text, description = '内容') {
    if (!text || text === '-') {
        showToast(`${description}为空，无法复制`, 'warning');
        return;
    }

    navigator.clipboard.writeText(text).then(() => {
        showToast(`${description}已复制到剪贴板`, 'success');
    }).catch(() => {
        // 降级方案：创建临时文本框
        const textArea = document.createElement('textarea');
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.select();
        try {
            document.execCommand('copy');
            showToast(`${description}已复制到剪贴板`, 'success');
        } catch (err) {
            showToast('复制失败，请手动复制', 'error');
        }
        document.body.removeChild(textArea);
    });
}

// 删除Cookie
async function delCookie(id) {
    if (!confirm(`确定要删除账号 "${id}" 吗？此操作不可恢复。`)) return;

    try {
    await fetchJSON(apiBase + `/cookies/${id}`, { method: 'DELETE' });
    showToast(`账号 "${id}" 已删除`, 'success');
    loadCookies();
    } catch (err) {
    // 错误已在fetchJSON中处理
    }
}

// 内联编辑Cookie
function editCookieInline(id, currentValue) {
    const row = event.target.closest('tr');
    const cookieValueCell = row.querySelector('.cookie-value');
    const originalContent = cookieValueCell.innerHTML;

    // 存储原始数据到全局变量，避免HTML注入问题
    window.editingCookieData = {
    id: id,
    originalContent: originalContent,
    originalValue: currentValue || ''
    };

    // 创建编辑界面容器
    const editContainer = document.createElement('div');
    editContainer.className = 'd-flex gap-2';

    // 创建输入框
    const input = document.createElement('input');
    input.type = 'text';
    input.className = 'form-control form-control-sm';
    input.id = `edit-${id}`;
    input.value = currentValue || '';
    input.placeholder = '输入新的Cookie值';

    // 创建保存按钮
    const saveBtn = document.createElement('button');
    saveBtn.className = 'btn btn-sm btn-success';
    saveBtn.title = '保存';
    saveBtn.innerHTML = '<i class="bi bi-check"></i>';
    saveBtn.onclick = () => saveCookieInline(id);

    // 创建取消按钮
    const cancelBtn = document.createElement('button');
    cancelBtn.className = 'btn btn-sm btn-secondary';
    cancelBtn.title = '取消';
    cancelBtn.innerHTML = '<i class="bi bi-x"></i>';
    cancelBtn.onclick = () => cancelCookieEdit(id);

    // 组装编辑界面
    editContainer.appendChild(input);
    editContainer.appendChild(saveBtn);
    editContainer.appendChild(cancelBtn);

    // 替换原内容
    cookieValueCell.innerHTML = '';
    cookieValueCell.appendChild(editContainer);

    // 聚焦输入框
    input.focus();
    input.select();

    // 添加键盘事件监听
    input.addEventListener('keydown', function(e) {
    if (e.key === 'Enter') {
        e.preventDefault();
        saveCookieInline(id);
    } else if (e.key === 'Escape') {
        e.preventDefault();
        cancelCookieEdit(id);
    }
    });

    // 禁用该行的其他按钮
    const actionButtons = row.querySelectorAll('.btn-group button');
    actionButtons.forEach(btn => btn.disabled = true);
}

// 保存内联编辑的Cookie
async function saveCookieInline(id) {
    const input = document.getElementById(`edit-${id}`);
    const newValue = input.value.trim();

    if (!newValue) {
    showToast('Cookie值不能为空', 'warning');
    return;
    }

    try {
    toggleLoading(true);

    await fetchJSON(apiBase + `/cookies/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
        id: id,
        value: newValue
        })
    });

    showToast(`账号 "${id}" Cookie已更新`, 'success');
    loadCookies(); // 重新加载列表

    } catch (err) {
    console.error('Cookie更新失败:', err);
    showToast(`Cookie更新失败: ${err.message || '未知错误'}`, 'danger');
    // 恢复原内容
    cancelCookieEdit(id);
    } finally {
    toggleLoading(false);
    }
}

// 取消Cookie编辑
function cancelCookieEdit(id) {
    if (!window.editingCookieData || window.editingCookieData.id !== id) {
    console.error('编辑数据不存在');
    return;
    }

    const row = document.querySelector(`#edit-${id}`).closest('tr');
    const cookieValueCell = row.querySelector('.cookie-value');

    // 恢复原内容
    cookieValueCell.innerHTML = window.editingCookieData.originalContent;

    // 恢复按钮状态
    const actionButtons = row.querySelectorAll('.btn-group button');
    actionButtons.forEach(btn => btn.disabled = false);

    // 清理全局数据
    delete window.editingCookieData;
}



// 切换账号启用/禁用状态
async function toggleAccountStatus(accountId, enabled) {
    try {
    toggleLoading(true);

    // 这里需要调用后端API来更新账号状态
    // 由于当前后端可能没有enabled字段，我们先在前端模拟
    // 实际项目中需要后端支持

    const response = await fetch(`${apiBase}/cookies/${accountId}/status`, {
        method: 'PUT',
        headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify({ enabled: enabled })
    });

    if (response.ok) {
        showToast(`账号 "${accountId}" 已${enabled ? '启用' : '禁用'}`, 'success');

        // 清除相关缓存，确保数据一致性
        clearKeywordCache();

        // 重新加载账号列表数据，确保状态同步
        await loadCookies();

        // 刷新自动回复页面的账号列表
        refreshAccountList();

        // 如果禁用的账号在自动回复页面被选中，更新显示
        const accountSelect = document.getElementById('accountSelect');
        if (accountSelect && accountSelect.value === accountId) {
        if (!enabled) {
            // 更新徽章显示禁用状态
            updateAccountBadge(accountId, false);
            showToast('账号已禁用，配置的关键词不会参与自动回复', 'warning');
        } else {
            // 更新徽章显示启用状态
            updateAccountBadge(accountId, true);
            showToast('账号已启用，配置的关键词将参与自动回复', 'success');
        }
        }

    } else {
        // 如果后端不支持，先在前端模拟
        console.warn('后端暂不支持账号状态切换，使用前端模拟');
        showToast(`账号 "${accountId}" 已${enabled ? '启用' : '禁用'} (前端模拟)`, enabled ? 'success' : 'warning');
        updateAccountRowStatus(accountId, enabled);
    }

    } catch (error) {
    console.error('切换账号状态失败:', error);

    // 后端不支持时的降级处理
    showToast(`账号 "${accountId}" 已${enabled ? '启用' : '禁用'} (本地模拟)`, enabled ? 'success' : 'warning');
    updateAccountRowStatus(accountId, enabled);

    // 恢复切换按钮状态
    const toggle = document.querySelector(`input[onchange*="${accountId}"]`);
    if (toggle) {
        toggle.checked = enabled;
    }
    } finally {
    toggleLoading(false);
    }
}

// 更新账号行的状态显示
function updateAccountRowStatus(accountId, enabled) {
    const toggle = document.querySelector(`input[onchange*="${accountId}"]`);
    if (!toggle) return;

    const row = toggle.closest('tr');
    const statusBadge = row.querySelector('.status-badge');
    const actionButtons = row.querySelectorAll('.btn-group .btn:not(.btn-outline-info):not(.btn-outline-danger)');

    // 更新行样式
    row.className = `account-row ${enabled ? 'enabled' : 'disabled'}`;

    // 更新状态徽章
    statusBadge.className = `status-badge ${enabled ? 'enabled' : 'disabled'}`;
    statusBadge.title = enabled ? '账号已启用' : '账号已禁用';
    statusBadge.innerHTML = `
    <i class="bi bi-${enabled ? 'check-circle-fill' : 'x-circle-fill'}"></i>
    `;

    // 更新按钮状态（只禁用编辑Cookie按钮，其他按钮保持可用）
    actionButtons.forEach(btn => {
    if (btn.onclick && btn.onclick.toString().includes('editCookieInline')) {
        btn.disabled = !enabled;
    }
    // 设置自动回复按钮始终可用，但更新提示文本
    if (btn.onclick && btn.onclick.toString().includes('goToAutoReply')) {
        btn.title = enabled ? '设置自动回复' : '配置关键词 (账号已禁用)';
    }
    });

    // 更新切换按钮的提示
    const label = toggle.closest('.status-toggle');
    label.title = enabled ? '点击禁用' : '点击启用';
}

// 切换自动确认发货状态
async function toggleAutoConfirm(accountId, enabled) {
    try {
    toggleLoading(true);

    const response = await fetch(`${apiBase}/cookies/${accountId}/auto-confirm`, {
        method: 'PUT',
        headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify({ auto_confirm: enabled })
    });

    if (response.ok) {
        const result = await response.json();
        showToast(result.message, 'success');

        // 更新界面显示
        updateAutoConfirmRowStatus(accountId, enabled);
    } else {
        const error = await response.json();
        showToast(error.detail || '更新自动确认发货设置失败', 'error');

        // 恢复切换按钮状态
        const toggle = document.querySelector(`input[onchange*="toggleAutoConfirm('${accountId}'"]`);
        if (toggle) {
        toggle.checked = !enabled;
        }
    }

    } catch (error) {
    console.error('切换自动确认发货状态失败:', error);
    showToast('网络错误，请稍后重试', 'error');

    // 恢复切换按钮状态
    const toggle = document.querySelector(`input[onchange*="toggleAutoConfirm('${accountId}'"]`);
    if (toggle) {
        toggle.checked = !enabled;
    }
    } finally {
    toggleLoading(false);
    }
}

// 更新自动确认发货行状态
function updateAutoConfirmRowStatus(accountId, enabled) {
    const row = document.querySelector(`tr:has(input[onchange*="toggleAutoConfirm('${accountId}'"])`);
    if (!row) return;

    const statusBadge = row.querySelector('.status-badge:has(i.bi-truck, i.bi-truck-flatbed)');
    const toggle = row.querySelector(`input[onchange*="toggleAutoConfirm('${accountId}'"]`);

    if (statusBadge && toggle) {
    // 更新状态徽章
    statusBadge.className = `status-badge ${enabled ? 'enabled' : 'disabled'}`;
    statusBadge.title = enabled ? '自动确认发货已开启' : '自动确认发货已关闭';
    statusBadge.innerHTML = `
        <i class="bi bi-${enabled ? 'truck' : 'truck-flatbed'}"></i>
    `;

    // 更新切换按钮的提示
    const label = toggle.closest('.status-toggle');
    label.title = enabled ? '点击关闭自动确认发货' : '点击开启自动确认发货';
    }
}

// 切换暂停功能开关状态
async function togglePauseEnabled(accountId, enabled) {
    try {
    toggleLoading(true);

    const response = await fetch(`${apiBase}/cookies/${accountId}/pause-enabled`, {
        method: 'PUT',
        headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify({ pause_enabled: enabled })
    });

    if (response.ok) {
        const result = await response.json();
        showToast(result.message, 'success');

        // 更新界面显示
        updatePauseEnabledRowStatus(accountId, enabled);
    } else {
        const error = await response.json();
        showToast(error.detail || '更新暂停功能开关失败', 'error');

        // 恢复切换按钮状态
        const toggle = document.querySelector(`input[onchange*="togglePauseEnabled('${accountId}'"]`);
        if (toggle) {
        toggle.checked = !enabled;
        }
    }

    } catch (error) {
    console.error('切换暂停功能开关失败:', error);
    showToast('网络错误，请稍后重试', 'error');

    // 恢复切换按钮状态
    const toggle = document.querySelector(`input[onchange*="togglePauseEnabled('${accountId}'"]`);
    if (toggle) {
        toggle.checked = !enabled;
    }
    } finally {
    toggleLoading(false);
    }
}

// 更新暂停功能开关行状态
function updatePauseEnabledRowStatus(accountId, enabled) {
    const row = document.querySelector(`tr:has(input[onchange*="togglePauseEnabled('${accountId}'"])`);
    if (!row) return;

    const statusBadge = row.querySelector('.status-badge:has(i.bi-pause-circle-fill, i.bi-play-circle-fill)');
    const toggle = row.querySelector(`input[onchange*="togglePauseEnabled('${accountId}'"]`);

    if (statusBadge && toggle) {
    // 更新状态徽章
    statusBadge.className = `status-badge ${enabled ? 'enabled' : 'disabled'}`;
    statusBadge.title = enabled ? '暂停功能已启用' : '暂停功能已禁用';
    statusBadge.innerHTML = `
        <i class="bi bi-${enabled ? 'pause-circle-fill' : 'play-circle-fill'}"></i>
    `;

    // 更新切换按钮的提示
    const label = toggle.closest('.status-toggle');
    label.title = enabled ? '点击关闭暂停功能' : '点击开启暂停功能';
    }
}

// 跳转到自动回复页面并选择指定账号
function goToAutoReply(accountId) {
    // 切换到自动回复页面
    showSection('auto-reply');

    // 设置账号选择器的值
    setTimeout(() => {
    const accountSelect = document.getElementById('accountSelect');
    if (accountSelect) {
        accountSelect.value = accountId;
        // 触发change事件来加载关键词
        loadAccountKeywords();
    }
    }, 100);

    showToast(`已切换到自动回复页面，账号 "${accountId}" 已选中`, 'info');
}





// 登出功能
async function logout() {
    try {
    if (authToken) {
        await fetch('/logout', {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
        });
    }
    localStorage.removeItem('auth_token');
    window.location.href = '/';
    } catch (err) {
    console.error('登出失败:', err);
    localStorage.removeItem('auth_token');
    window.location.href = '/';
    }
}

// 检查认证状态
async function checkAuth() {
    if (!authToken) {
    window.location.href = '/';
    return false;
    }

    try {
    const response = await fetch('/verify', {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });
    const result = await response.json();

    if (!result.authenticated) {
        localStorage.removeItem('auth_token');
        window.location.href = '/';
        return false;
    }

    // 存储当前用户信息
    currentUserInfo = {
        user_id: result.user_id,
        username: result.username,
        is_admin: result.is_admin
    };
    
    // 基于角色和权限显示菜单
    if (result.menus && result.menus.length > 0) {
        updateMenuVisibility(result.menus, result.permissions);
    }
    
    // 兼容旧的管理员检查（保持向后兼容）
    if (result.is_admin === true) {
        const adminMenuSection = document.getElementById('adminMenuSection');
        if (adminMenuSection) {
        adminMenuSection.style.display = 'block';
        }

        // 显示备份管理功能
        const backupManagement = document.getElementById('backup-management');
        if (backupManagement) {
        backupManagement.style.display = 'block';
        }

        // 显示注册设置功能
        const registrationSettings = document.getElementById('registration-settings');
        if (registrationSettings) {
        registrationSettings.style.display = 'block';
        }
    }

    return true;
    } catch (err) {
    localStorage.removeItem('auth_token');
    window.location.href = '/';
    return false;
    }
}

// 全局变量存储用户权限
let currentUserPermissions = null; // 初始为null，表示未加载

// 全局变量存储门店词库数据
let allKeywordLibraries = [];

// 全局变量存储当前用户信息
let currentUserInfo = null;

// 检查用户是否有自动回复管理权限的辅助函数
function hasAutoReplyManagePermission() {
    // 确保admin用户总是有管理权限
    const isAdminUser = currentUserInfo && (currentUserInfo.username === 'admin' || currentUserInfo.is_admin === true);
    const hasPermission = (Array.isArray(currentUserPermissions) && currentUserPermissions.includes('auto_reply_manage'));
    
    return isAdminUser || hasPermission;
}

// 基于用户菜单权限更新菜单显示
function updateMenuVisibility(userMenus, userPermissions) {
    // 存储用户权限到全局变量
    currentUserPermissions = userPermissions || [];
    // 菜单键与DOM元素的映射
    const menuMapping = {
        'dashboard': { selector: '[onclick="showSection(\'dashboard\')"]', section: 'dashboard-section' },
        'accounts': { selector: '[onclick="showSection(\'accounts\')"]', section: 'accounts-section' },
        'items': { selector: '[onclick="showSection(\'items\')"]', section: 'items-section' },
        'orders': { selector: '[onclick="showSection(\'orders\')"]', section: 'orders-section' },
        'auto-reply': { selector: '[onclick="showSection(\'auto-reply\')"]', section: 'auto-reply-section' },
        'keyword-library': { selector: '[onclick="showSection(\'keyword-library\')"]', section: 'keyword-library-section' },
        'global-keywords': { selector: '[onclick="showSection(\'global-keywords\')"]', section: 'global-keywords-section' },
        'cards': { selector: '[onclick="showSection(\'cards\')"]', section: 'cards-section' },
        'auto-delivery': { selector: '[onclick="showSection(\'auto-delivery\')"]', section: 'auto-delivery-section' },
        'notification-channels': { selector: '[onclick="showSection(\'notification-channels\')"]', section: 'notification-channels-section' },
        'message-notifications': { selector: '[onclick="showSection(\'message-notifications\')"]', section: 'message-notifications-section' },
        'system-settings': { selector: '[onclick="showSection(\'system-settings\')"]', section: 'system-settings-section' },
        'admin-section': { selector: '#adminMenuSection' },
        'user-management': { selector: 'a[href="/user_management.html"]' },
        'log-management': { selector: 'a[href="/log_management.html"]' },
        'data-management': { selector: 'a[href="/data_management.html"]' },
        'about': { selector: '[onclick="showSection(\'about\')"]', section: 'about-section' }
    };
    
    // 获取用户可见的菜单键
    const visibleMenuKeys = userMenus.map(menu => menu.menu_key);
    
    // 首先隐藏所有菜单项
    Object.keys(menuMapping).forEach(menuKey => {
        const mapping = menuMapping[menuKey];
        const menuElement = document.querySelector(mapping.selector);
        if (menuElement) {
            if (menuKey === 'admin-section') {
                // 特殊处理管理员菜单区域
                menuElement.style.display = 'none';
            } else {
                // 隐藏菜单项的父级nav-item
                const navItem = menuElement.closest('.nav-item');
                if (navItem) {
                    navItem.style.display = 'none';
                }
            }
        }
    });
    
    // 显示用户有权限的菜单
    visibleMenuKeys.forEach(menuKey => {
        const mapping = menuMapping[menuKey];
        if (mapping) {
            const menuElement = document.querySelector(mapping.selector);
            if (menuElement) {
                if (menuKey === 'admin-section') {
                    // 特殊处理管理员菜单区域
                    menuElement.style.display = 'block';
                } else {
                    // 显示菜单项的父级nav-item
                    const navItem = menuElement.closest('.nav-item');
                    if (navItem) {
                        navItem.style.display = 'block';
                    }
                }
            }
        }
    });
    
    // 基于权限控制页面内的功能显示
    updateFeatureVisibility(userPermissions);
}

// 基于用户权限控制页面功能显示
function updateFeatureVisibility(userPermissions) {
    // 备份管理功能
    const backupManagement = document.getElementById('backup-management');
    if (backupManagement) {
        backupManagement.style.display = userPermissions.includes('data_management_access') ? 'block' : 'none';
    }
    
    // 注册设置功能
    const registrationSettings = document.getElementById('registration-settings');
    if (registrationSettings) {
        registrationSettings.style.display = userPermissions.includes('user_management_access') ? 'block' : 'none';
    }
    
    // 可以根据需要添加更多功能的权限控制
}

// 初始化事件监听
document.addEventListener('DOMContentLoaded', async () => {
    // 首先检查认证状态
    const isAuthenticated = await checkAuth();
    if (!isAuthenticated) return;

    // 绑定系统设置相关事件（确保在DOM加载完成后绑定）
    bindSystemSettingsEvents();
    // 添加Cookie表单提交
    document.getElementById('addForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const id = document.getElementById('cookieId').value.trim();
    const value = document.getElementById('cookieValue').value.trim();

    if (!id || !value) return;

    try {
        await fetchJSON(apiBase + '/cookies', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id, value })
        });

        document.getElementById('cookieId').value = '';
        document.getElementById('cookieValue').value = '';
        showToast(`账号 "${id}" 添加成功`);
        loadCookies();
    } catch (err) {
        // 错误已在fetchJSON中处理
    }
    });

    // 增强的键盘快捷键和用户体验
    document.getElementById('newKeyword')?.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        e.preventDefault();
        document.getElementById('newReply').focus();
    }
    });

    document.getElementById('newReply')?.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        e.preventDefault();
        addKeyword();
    }
    });

    // ESC键取消编辑
    document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape' && typeof window.editingIndex !== 'undefined') {
        e.preventDefault();
        cancelEdit();
    }
    });

    // 输入框实时验证和提示
    document.getElementById('newKeyword')?.addEventListener('input', function(e) {
    const value = e.target.value.trim();
    const addBtn = document.querySelector('.add-btn');
    const replyInput = document.getElementById('newReply');

    if (value.length > 0) {
        e.target.style.borderColor = '#10b981';
        if (replyInput.value.trim().length > 0) {
        addBtn.style.opacity = '1';
        addBtn.style.transform = 'scale(1)';
        }
    } else {
        e.target.style.borderColor = '#e5e7eb';
        addBtn.style.opacity = '0.7';
        addBtn.style.transform = 'scale(0.95)';
    }
    });

    document.getElementById('newReply')?.addEventListener('input', function(e) {
    const value = e.target.value.trim();
    const addBtn = document.querySelector('.add-btn');
    const keywordInput = document.getElementById('newKeyword');

    if (value.length > 0) {
        e.target.style.borderColor = '#10b981';
        if (keywordInput.value.trim().length > 0) {
        addBtn.style.opacity = '1';
        addBtn.style.transform = 'scale(1)';
        }
    } else {
        e.target.style.borderColor = '#e5e7eb';
        addBtn.style.opacity = '0.7';
        addBtn.style.transform = 'scale(0.95)';
    }
    });

    // 初始加载仪表盘
    loadDashboard();

    // 初始化图片关键词事件监听器
    initImageKeywordEventListeners();

    // 初始化搜索键盘监听器
    document.getElementById('searchKeyword')?.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            searchKeywords();
        }
    });

    // 初始化卡券图片文件选择器
    initCardImageFileSelector();

    // 初始化编辑卡券图片文件选择器
    initEditCardImageFileSelector();

    // 初始化工具提示
    initTooltips();

    // 点击侧边栏外部关闭移动端菜单
    document.addEventListener('click', function(e) {
    const sidebar = document.getElementById('sidebar');
    const toggle = document.querySelector('.mobile-toggle');

    if (window.innerWidth <= 768 &&
        !sidebar.contains(e.target) &&
        !toggle.contains(e.target) &&
        sidebar.classList.contains('show')) {
        sidebar.classList.remove('show');
    }
    });
});

// ==================== 默认回复管理功能 ====================

// 打开默认回复管理器
async function openDefaultReplyManager() {
    try {
    await loadDefaultReplies();
    const modal = new bootstrap.Modal(document.getElementById('defaultReplyModal'));
    modal.show();
    } catch (error) {
    console.error('打开默认回复管理器失败:', error);
    showToast('打开默认回复管理器失败', 'danger');
    }
}

// 加载默认回复列表
async function loadDefaultReplies() {
    try {
    // 获取所有账号
    const accountsResponse = await fetch(`${apiBase}/cookies`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (!accountsResponse.ok) {
        throw new Error('获取账号列表失败');
    }

    const accounts = await accountsResponse.json();

    // 获取所有默认回复设置
    const repliesResponse = await fetch(`${apiBase}/default-replies`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    let defaultReplies = {};
    if (repliesResponse.ok) {
        defaultReplies = await repliesResponse.json();
    }

    renderDefaultRepliesList(accounts, defaultReplies);
    } catch (error) {
    console.error('加载默认回复列表失败:', error);
    showToast('加载默认回复列表失败', 'danger');
    }
}

// 渲染默认回复列表
function renderDefaultRepliesList(accounts, defaultReplies) {
    const tbody = document.getElementById('defaultReplyTableBody');
    tbody.innerHTML = '';

    if (accounts.length === 0) {
    tbody.innerHTML = `
        <tr>
        <td colspan="5" class="text-center py-4 text-muted">
            <i class="bi bi-chat-text fs-1 d-block mb-3"></i>
            <h5>暂无账号数据</h5>
            <p class="mb-0">请先添加账号</p>
        </td>
        </tr>
    `;
    return;
    }

    accounts.forEach(accountId => {
    const replySettings = defaultReplies[accountId] || { enabled: false, reply_content: '', reply_once: false };
    const tr = document.createElement('tr');

    // 状态标签
    const statusBadge = replySettings.enabled ?
        '<span class="badge bg-success">启用</span>' :
        '<span class="badge bg-secondary">禁用</span>';

    // 只回复一次标签
    const replyOnceBadge = replySettings.reply_once ?
        '<span class="badge bg-warning">是</span>' :
        '<span class="badge bg-light text-dark">否</span>';

    // 回复内容预览
    let contentPreview = replySettings.reply_content || '未设置';
    if (contentPreview.length > 50) {
        contentPreview = contentPreview.substring(0, 50) + '...';
    }

    tr.innerHTML = `
        <td>
        <strong class="text-primary">${accountId}</strong>
        </td>
        <td>${statusBadge}</td>
        <td>${replyOnceBadge}</td>
        <td>
        <div class="text-truncate" style="max-width: 300px;" title="${replySettings.reply_content || ''}">
            ${contentPreview}
        </div>
        </td>
        <td>
        <div class="btn-group" role="group">
            <button class="btn btn-sm btn-outline-primary" onclick="editDefaultReply('${accountId}')" title="编辑">
            <i class="bi bi-pencil"></i>
            </button>
            <button class="btn btn-sm btn-outline-info" onclick="testDefaultReply('${accountId}')" title="测试">
            <i class="bi bi-play"></i>
            </button>
            ${replySettings.reply_once ? `
            <button class="btn btn-sm btn-outline-warning" onclick="clearDefaultReplyRecords('${accountId}')" title="清空记录">
            <i class="bi bi-arrow-clockwise"></i>
            </button>
            ` : ''}
        </div>
        </td>
    `;

    tbody.appendChild(tr);
    });
}

// 编辑默认回复
async function editDefaultReply(accountId) {
    try {
    // 获取当前设置
    const response = await fetch(`${apiBase}/default-replies/${accountId}`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    let settings = { enabled: false, reply_content: '', reply_once: false };
    if (response.ok) {
        settings = await response.json();
    }

    // 填充编辑表单
    document.getElementById('editAccountId').value = accountId;
    document.getElementById('editAccountIdDisplay').value = accountId;
    document.getElementById('editDefaultReplyEnabled').checked = settings.enabled;
    document.getElementById('editReplyContent').value = settings.reply_content || '';
    document.getElementById('editReplyOnce').checked = settings.reply_once || false;

    // 根据启用状态显示/隐藏内容输入框
    toggleReplyContentVisibility();

    // 显示编辑模态框
    const modal = new bootstrap.Modal(document.getElementById('editDefaultReplyModal'));
    modal.show();
    } catch (error) {
    console.error('获取默认回复设置失败:', error);
    showToast('获取默认回复设置失败', 'danger');
    }
}

// 切换回复内容输入框的显示/隐藏
function toggleReplyContentVisibility() {
    const enabled = document.getElementById('editDefaultReplyEnabled').checked;
    const contentGroup = document.getElementById('editReplyContentGroup');
    contentGroup.style.display = enabled ? 'block' : 'none';
}

// 保存默认回复设置
async function saveDefaultReply() {
    try {
    const accountId = document.getElementById('editAccountId').value;
    const enabled = document.getElementById('editDefaultReplyEnabled').checked;
    const replyContent = document.getElementById('editReplyContent').value;
    const replyOnce = document.getElementById('editReplyOnce').checked;

    if (enabled && !replyContent.trim()) {
        showToast('启用默认回复时必须设置回复内容', 'warning');
        return;
    }

    const data = {
        enabled: enabled,
        reply_content: enabled ? replyContent : null,
        reply_once: replyOnce
    };

    const response = await fetch(`${apiBase}/default-replies/${accountId}`, {
        method: 'PUT',
        headers: {
        'Authorization': `Bearer ${authToken}`,
        'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    });

    if (response.ok) {
        showToast('默认回复设置保存成功', 'success');
        bootstrap.Modal.getInstance(document.getElementById('editDefaultReplyModal')).hide();
        loadDefaultReplies(); // 刷新列表
        loadCookies(); // 刷新账号列表以更新默认回复状态显示
    } else {
        const error = await response.text();
        showToast(`保存失败: ${error}`, 'danger');
    }
    } catch (error) {
    console.error('保存默认回复设置失败:', error);
    showToast('保存默认回复设置失败', 'danger');
    }
}

// 测试默认回复（占位函数）
function testDefaultReply(accountId) {
    showToast('测试功能开发中...', 'info');
}

// 刷新Token状态
async function refreshTokenStatus(cookieId) {
    try {
        const response = await fetch(`${apiBase}/cookies/${cookieId}/refresh-token-status`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.ok) {
            const result = await response.json();
            showToast(`账号 ${cookieId} Token状态已刷新: ${result.token_status}`, 'success');
            // 重新加载Cookie列表以更新显示
            loadCookies();
        } else {
            const error = await response.text();
            showToast(`刷新Token状态失败: ${error}`, 'danger');
        }
    } catch (error) {
        console.error('刷新Token状态失败:', error);
        showToast('刷新Token状态失败', 'danger');
    }
}

// 清空默认回复记录
async function clearDefaultReplyRecords(accountId) {
    if (!confirm(`确定要清空账号 "${accountId}" 的默认回复记录吗？\n\n清空后，该账号将可以重新对之前回复过的对话进行默认回复。`)) {
        return;
    }

    try {
        const response = await fetch(`${apiBase}/default-replies/${accountId}/clear-records`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.ok) {
            showToast(`账号 "${accountId}" 的默认回复记录已清空`, 'success');
            loadDefaultReplies(); // 刷新列表
        } else {
            const error = await response.text();
            showToast(`清空失败: ${error}`, 'danger');
        }
    } catch (error) {
        console.error('清空默认回复记录失败:', error);
        showToast('清空默认回复记录失败', 'danger');
    }
}

// ==================== AI回复配置相关函数 ====================

// 配置AI回复
async function configAIReply(accountId) {
    try {
    // 获取当前AI回复设置
    const settings = await fetchJSON(`${apiBase}/ai-reply-settings/${accountId}`);

    // 填充表单
    document.getElementById('aiConfigAccountId').value = accountId;
    document.getElementById('aiConfigAccountIdDisplay').value = accountId;
    document.getElementById('aiReplyEnabled').checked = settings.ai_enabled;
    // 处理模型名称
    const modelSelect = document.getElementById('aiModelName');
    const customModelInput = document.getElementById('customModelName');
    const modelName = settings.model_name;
    // 检查是否是预设模型
    const presetModels = ['qwen-plus', 'qwen-turbo', 'qwen-max', 'gpt-3.5-turbo', 'gpt-4'];
    if (presetModels.includes(modelName)) {
        modelSelect.value = modelName;
        customModelInput.style.display = 'none';
        customModelInput.value = '';
    } else {
        // 自定义模型
        modelSelect.value = 'custom';
        customModelInput.style.display = 'block';
        customModelInput.value = modelName;
    }
    document.getElementById('aiBaseUrl').value = settings.base_url;
    document.getElementById('aiApiKey').value = settings.api_key;
    document.getElementById('maxDiscountPercent').value = settings.max_discount_percent;
    document.getElementById('maxDiscountAmount').value = settings.max_discount_amount;
    document.getElementById('maxBargainRounds').value = settings.max_bargain_rounds;
    document.getElementById('customPrompts').value = settings.custom_prompts;

    // 切换设置显示状态
    toggleAIReplySettings();

    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('aiReplyConfigModal'));
    modal.show();

    } catch (error) {
    console.error('获取AI回复设置失败:', error);
    showToast('获取AI回复设置失败', 'danger');
    }
}

// 切换AI回复设置显示
function toggleAIReplySettings() {
    const enabled = document.getElementById('aiReplyEnabled').checked;
    const settingsDiv = document.getElementById('aiReplySettings');
    const bargainSettings = document.getElementById('bargainSettings');
    const promptSettings = document.getElementById('promptSettings');
    const testArea = document.getElementById('testArea');

    if (enabled) {
    settingsDiv.style.display = 'block';
    bargainSettings.style.display = 'block';
    promptSettings.style.display = 'block';
    testArea.style.display = 'block';
    } else {
    settingsDiv.style.display = 'none';
    bargainSettings.style.display = 'none';
    promptSettings.style.display = 'none';
    testArea.style.display = 'none';
    }
}

// 保存AI回复配置
async function saveAIReplyConfig() {
    try {
    const accountId = document.getElementById('aiConfigAccountId').value;
    const enabled = document.getElementById('aiReplyEnabled').checked;

    // 如果启用AI回复，验证必填字段
    if (enabled) {
        const apiKey = document.getElementById('aiApiKey').value.trim();
        if (!apiKey) {
        showToast('请输入API密钥', 'warning');
        return;
        }

        // 验证自定义提示词格式
        const customPrompts = document.getElementById('customPrompts').value.trim();
        if (customPrompts) {
        try {
            JSON.parse(customPrompts);
        } catch (e) {
            showToast('自定义提示词格式错误，请检查JSON格式', 'warning');
            return;
        }
        }
    }
// 获取模型名称
    let modelName = document.getElementById('aiModelName').value;
    if (modelName === 'custom') {
        const customModelName = document.getElementById('customModelName').value.trim();
        if (!customModelName) {
        showToast('请输入自定义模型名称', 'warning');
        return;
        }
        modelName = customModelName;
    }
    // 构建设置对象
    const settings = {
        ai_enabled: enabled,
        model_name: modelName,
        api_key: document.getElementById('aiApiKey').value,
        base_url: document.getElementById('aiBaseUrl').value,
        max_discount_percent: parseInt(document.getElementById('maxDiscountPercent').value),
        max_discount_amount: parseInt(document.getElementById('maxDiscountAmount').value),
        max_bargain_rounds: parseInt(document.getElementById('maxBargainRounds').value),
        custom_prompts: document.getElementById('customPrompts').value
    };

    // 保存设置
    const response = await fetch(`${apiBase}/ai-reply-settings/${accountId}`, {
        method: 'PUT',
        headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify(settings)
    });

    if (response.ok) {
        showToast('AI回复配置保存成功', 'success');
        bootstrap.Modal.getInstance(document.getElementById('aiReplyConfigModal')).hide();
        loadCookies(); // 刷新账号列表以更新AI回复状态显示
    } else {
        const error = await response.text();
        showToast(`保存失败: ${error}`, 'danger');
    }

    } catch (error) {
    console.error('保存AI回复配置失败:', error);
    showToast('保存AI回复配置失败', 'danger');
    }
}

// 测试AI回复
async function testAIReply() {
    try {
    const accountId = document.getElementById('aiConfigAccountId').value;
    const testMessage = document.getElementById('testMessage').value.trim();
    const testItemPrice = document.getElementById('testItemPrice').value;

    if (!testMessage) {
        showToast('请输入测试消息', 'warning');
        return;
    }

    // 构建测试数据
    const testData = {
        message: testMessage,
        item_title: '测试商品',
        item_price: parseFloat(testItemPrice) || 100,
        item_desc: '这是一个用于测试AI回复功能的商品'
    };

    // 显示加载状态
    const testResult = document.getElementById('testResult');
    const testReplyContent = document.getElementById('testReplyContent');
    testResult.style.display = 'block';
    testReplyContent.innerHTML = '<i class="bi bi-hourglass-split"></i> 正在生成AI回复...';

    // 调用测试API
    const response = await fetch(`${apiBase}/ai-reply-test/${accountId}`, {
        method: 'POST',
        headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify(testData)
    });

    if (response.ok) {
        const result = await response.json();
        testReplyContent.innerHTML = result.reply;
        showToast('AI回复测试成功', 'success');
    } else {
        const error = await response.text();
        testReplyContent.innerHTML = `<span class="text-danger">测试失败: ${error}</span>`;
        showToast(`测试失败: ${error}`, 'danger');
    }

    } catch (error) {
    console.error('测试AI回复失败:', error);
    const testReplyContent = document.getElementById('testReplyContent');
    testReplyContent.innerHTML = `<span class="text-danger">测试失败: ${error.message}</span>`;
    showToast('测试AI回复失败', 'danger');
    }
}

// 切换自定义模型输入框的显示/隐藏
function toggleCustomModelInput() {
    const modelSelect = document.getElementById('aiModelName');
    const customModelInput = document.getElementById('customModelName');
    if (modelSelect.value === 'custom') {
    customModelInput.style.display = 'block';
    customModelInput.focus();
    } else {
    customModelInput.style.display = 'none';
    customModelInput.value = '';
    }
}

// 监听默认回复启用状态变化
document.addEventListener('DOMContentLoaded', function() {
    const enabledCheckbox = document.getElementById('editDefaultReplyEnabled');
    if (enabledCheckbox) {
    enabledCheckbox.addEventListener('change', toggleReplyContentVisibility);
    }
});

// ================================
// 【通知渠道菜单】相关功能
// ================================

// 通知渠道类型配置
const channelTypeConfigs = {
    dingtalk: {
    title: '钉钉通知',
    description: '请设置钉钉机器人Webhook URL，支持自定义机器人和群机器人',
    icon: 'bi-bell-fill',
    color: 'info',
    fields: [
        {
        id: 'webhook_url',
        label: '钉钉机器人Webhook URL',
        type: 'url',
        placeholder: 'https://oapi.dingtalk.com/robot/send?access_token=...',
        required: true,
        help: '钉钉机器人的Webhook地址'
        },
        {
        id: 'secret',
        label: '加签密钥（可选）',
        type: 'text',
        placeholder: '输入加签密钥',
        required: false,
        help: '如果机器人开启了加签验证，请填写密钥'
        }
    ]
    },
    email: {
    title: '邮件通知',
    description: '通过SMTP服务器发送邮件通知，支持各种邮箱服务商',
    icon: 'bi-envelope-fill',
    color: 'success',
    fields: [
        {
        id: 'smtp_server',
        label: 'SMTP服务器',
        type: 'text',
        placeholder: 'smtp.gmail.com',
        required: true,
        help: '邮箱服务商的SMTP服务器地址'
        },
        {
        id: 'smtp_port',
        label: 'SMTP端口',
        type: 'number',
        placeholder: '587',
        required: true,
        help: '通常为587（TLS）或465（SSL）'
        },
        {
        id: 'email_user',
        label: '发送邮箱',
        type: 'email',
        placeholder: 'your-email@gmail.com',
        required: true,
        help: '用于发送通知的邮箱地址'
        },
        {
        id: 'email_password',
        label: '邮箱密码/授权码',
        type: 'password',
        placeholder: '输入密码或授权码',
        required: true,
        help: '邮箱密码或应用专用密码'
        },
        {
        id: 'recipient_email',
        label: '接收邮箱',
        type: 'email',
        placeholder: 'recipient@example.com',
        required: true,
        help: '用于接收通知的邮箱地址'
        }
    ]
    },
    webhook: {
    title: 'Webhook通知',
    description: '通过HTTP POST请求发送通知到自定义的Webhook地址，支持微信机器人API格式',
    icon: 'bi-link-45deg',
    color: 'warning',
    fields: [
        {
        id: 'webhook_url',
        label: 'Webhook URL',
        type: 'url',
        placeholder: 'http://home.jhsrvip.cn:7777/qianxun/httpapi',
        required: true,
        help: '接收通知的Webhook基础地址'
        },
        {
        id: 'wxid_param',
        label: '机器人WXID参数',
        type: 'text',
        placeholder: 'wxid_b0wfqf3ostad22',
        required: false,
        help: 'URL参数中的wxid值，如果填写将自动拼接到URL中'
        },
        {
        id: 'target_wxid',
        label: '目标微信群ID',
        type: 'text',
        placeholder: '49172401685@chatroom',
        required: false,
        help: '消息发送的目标微信群ID或好友wxid'
        },
        {
        id: 'api_format',
        label: 'API格式',
        type: 'select',
        options: [
            { value: 'wechat_bot', text: '微信机器人格式', selected: true },
            { value: 'generic', text: '通用格式' }
        ],
        required: true,
        help: '选择API数据格式类型'
        },
        {
        id: 'http_method',
        label: 'HTTP方法',
        type: 'select',
        options: [
            { value: 'POST', text: 'POST' },
            { value: 'PUT', text: 'PUT' }
        ],
        required: true,
        help: '发送请求使用的HTTP方法'
        },
        {
        id: 'headers',
        label: '自定义请求头（可选）',
        type: 'textarea',
        placeholder: '{"Authorization": "Bearer token", "User-Agent": "Custom/1.0"}',
        required: false,
        help: 'JSON格式的自定义请求头'
        }
    ]
    },
    wechat: {
    title: '微信通知',
    description: '通过企业微信机器人发送通知消息',
    icon: 'bi-wechat',
    color: 'success',
    fields: [
        {
        id: 'webhook_url',
        label: '企业微信机器人Webhook URL',
        type: 'url',
        placeholder: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...',
        required: true,
        help: '企业微信群机器人的Webhook地址'
        }
    ]
    },
    telegram: {
    title: 'Telegram通知',
    description: '通过Telegram机器人发送通知消息',
    icon: 'bi-telegram',
    color: 'primary',
    fields: [
        {
        id: 'bot_token',
        label: 'Bot Token',
        type: 'text',
        placeholder: '123456789:ABCdefGHIjklMNOpqrsTUVwxyz',
        required: true,
        help: '从@BotFather获取的机器人Token'
        },
        {
        id: 'chat_id',
        label: 'Chat ID',
        type: 'text',
        placeholder: '123456789 或 @channel_name',
        required: true,
        help: '接收消息的用户ID或频道名'
        }
    ]
    }
};

// 显示添加渠道模态框
function showAddChannelModal(type) {
    const config = channelTypeConfigs[type];
    if (!config) {
    showToast('不支持的通知渠道类型', 'danger');
    return;
    }

    // 设置模态框标题和描述
    document.getElementById('addChannelModalTitle').textContent = `添加${config.title}`;
    document.getElementById('channelTypeDescription').innerHTML = config.description;
    document.getElementById('channelType').value = type;

    // 生成配置字段
    const fieldsContainer = document.getElementById('channelConfigFields');
    fieldsContainer.innerHTML = '';

    config.fields.forEach(field => {
    const fieldHtml = generateFieldHtml(field, '');
    fieldsContainer.insertAdjacentHTML('beforeend', fieldHtml);
    });

    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('addChannelModal'));
    modal.show();
}

// 生成表单字段HTML
function generateFieldHtml(field, prefix) {
    const fieldId = prefix + field.id;
    let inputHtml = '';

    switch (field.type) {
    case 'select':
        inputHtml = `<select class="form-select" id="${fieldId}" ${field.required ? 'required' : ''}>`;
        if (field.options) {
        field.options.forEach(option => {
            const selected = option.selected ? 'selected' : '';
            inputHtml += `<option value="${option.value}" ${selected}>${option.text}</option>`;
        });
        }
        inputHtml += '</select>';
        break;
    case 'textarea':
        inputHtml = `<textarea class="form-control" id="${fieldId}" placeholder="${field.placeholder}" rows="3" ${field.required ? 'required' : ''}></textarea>`;
        break;
    default:
        inputHtml = `<input type="${field.type}" class="form-control" id="${fieldId}" placeholder="${field.placeholder}" ${field.required ? 'required' : ''}>`;
    }

    return `
    <div class="mb-3">
        <label for="${fieldId}" class="form-label">
        ${field.label} ${field.required ? '<span class="text-danger">*</span>' : ''}
        </label>
        ${inputHtml}
        ${field.help ? `<small class="form-text text-muted">${field.help}</small>` : ''}
    </div>
    `;
}

// 保存通知渠道
async function saveNotificationChannel() {
    const type = document.getElementById('channelType').value;
    const name = document.getElementById('channelName').value;
    const enabled = document.getElementById('channelEnabled').checked;

    if (!name.trim()) {
    showToast('请输入渠道名称', 'warning');
    return;
    }

    const config = channelTypeConfigs[type];
    if (!config) {
    showToast('无效的渠道类型', 'danger');
    return;
    }

    // 收集配置数据
    const configData = {};
    let hasError = false;

    config.fields.forEach(field => {
    const element = document.getElementById(field.id);
    const value = element.value.trim();

    if (field.required && !value) {
        showToast(`请填写${field.label}`, 'warning');
        hasError = true;
        return;
    }

    if (value) {
        configData[field.id] = value;
    }
    });

    if (hasError) return;

    try {
    const response = await fetch(`${apiBase}/notification-channels`, {
        method: 'POST',
        headers: {
        'Authorization': `Bearer ${authToken}`,
        'Content-Type': 'application/json'
        },
        body: JSON.stringify({
        name: name,
        type: type,
        config: JSON.stringify(configData),
        enabled: enabled
        })
    });

    if (response.ok) {
        showToast('通知渠道添加成功', 'success');
        const modal = bootstrap.Modal.getInstance(document.getElementById('addChannelModal'));
        modal.hide();
        loadNotificationChannels();
    } else {
        const error = await response.text();
        showToast(`添加失败: ${error}`, 'danger');
    }
    } catch (error) {
    console.error('添加通知渠道失败:', error);
    showToast('添加通知渠道失败', 'danger');
    }
}

// 加载通知渠道列表
async function loadNotificationChannels() {
    try {
    const response = await fetch(`${apiBase}/notification-channels`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (!response.ok) {
        throw new Error('获取通知渠道失败');
    }

    const channels = await response.json();
    renderNotificationChannels(channels);
    } catch (error) {
    console.error('加载通知渠道失败:', error);
    showToast('加载通知渠道失败', 'danger');
    }
}

// 渲染通知渠道列表
function renderNotificationChannels(channels) {
    const tbody = document.getElementById('channelsTableBody');
    tbody.innerHTML = '';

    if (channels.length === 0) {
    tbody.innerHTML = `
        <tr>
        <td colspan="6" class="text-center py-4 text-muted">
            <i class="bi bi-bell fs-1 d-block mb-3"></i>
            <h5>暂无通知渠道</h5>
            <p class="mb-0">点击上方按钮添加通知渠道</p>
        </td>
        </tr>
    `;
    return;
    }

    channels.forEach(channel => {
    const tr = document.createElement('tr');

    const statusBadge = channel.enabled ?
        '<span class="badge bg-success">启用</span>' :
        '<span class="badge bg-secondary">禁用</span>';

    // 获取渠道类型配置（处理类型映射）
    let channelType = channel.type;
    if (channelType === 'ding_talk') {
        channelType = 'dingtalk';  // 兼容旧的类型名
    }
    const typeConfig = channelTypeConfigs[channelType];
    const typeDisplay = typeConfig ? typeConfig.title : channel.type;
    const typeColor = typeConfig ? typeConfig.color : 'secondary';

    // 解析并显示配置信息
    let configDisplay = '';
    try {
        const configData = JSON.parse(channel.config || '{}');
        const configEntries = Object.entries(configData);

        if (configEntries.length > 0) {
        configDisplay = configEntries.map(([key, value]) => {
            // 隐藏敏感信息
            if (key.includes('password') || key.includes('token') || key.includes('secret')) {
            return `${key}: ****`;
            }
            // 截断过长的值
            const displayValue = value.length > 30 ? value.substring(0, 30) + '...' : value;
            return `${key}: ${displayValue}`;
        }).join('<br>');
        } else {
        configDisplay = channel.config || '无配置';
        }
    } catch (e) {
        // 兼容旧格式
        configDisplay = channel.config || '无配置';
        if (configDisplay.length > 30) {
        configDisplay = configDisplay.substring(0, 30) + '...';
        }
    }

    tr.innerHTML = `
        <td><strong class="text-primary">${channel.id}</strong></td>
        <td>
        <div class="d-flex align-items-center">
            <i class="bi ${typeConfig ? typeConfig.icon : 'bi-bell'} me-2 text-${typeColor}"></i>
            ${channel.name}
        </div>
        </td>
        <td><span class="badge bg-${typeColor}">${typeDisplay}</span></td>
        <td><small class="text-muted">${configDisplay}</small></td>
        <td>${statusBadge}</td>
        <td>
        <div class="btn-group" role="group">
            <button class="btn btn-sm btn-outline-primary" onclick="editNotificationChannel(${channel.id})" title="编辑">
            <i class="bi bi-pencil"></i>
            </button>
            <button class="btn btn-sm btn-outline-danger" onclick="deleteNotificationChannel(${channel.id})" title="删除">
            <i class="bi bi-trash"></i>
            </button>
        </div>
        </td>
    `;

    tbody.appendChild(tr);
    });
}



// 删除通知渠道
async function deleteNotificationChannel(channelId) {
    if (!confirm('确定要删除这个通知渠道吗？')) {
    return;
    }

    try {
    const response = await fetch(`${apiBase}/notification-channels/${channelId}`, {
        method: 'DELETE',
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        showToast('通知渠道删除成功', 'success');
        loadNotificationChannels();
    } else {
        const error = await response.text();
        showToast(`删除失败: ${error}`, 'danger');
    }
    } catch (error) {
    console.error('删除通知渠道失败:', error);
    showToast('删除通知渠道失败', 'danger');
    }
}

// 编辑通知渠道
async function editNotificationChannel(channelId) {
    try {
    // 获取渠道详情
    const response = await fetch(`${apiBase}/notification-channels`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (!response.ok) {
        throw new Error('获取通知渠道失败');
    }

    const channels = await response.json();
    const channel = channels.find(c => c.id === channelId);

    if (!channel) {
        showToast('通知渠道不存在', 'danger');
        return;
    }

    // 处理类型映射
    let channelType = channel.type;
    if (channelType === 'ding_talk') {
        channelType = 'dingtalk';  // 兼容旧的类型名
    }

    const config = channelTypeConfigs[channelType];
    if (!config) {
        showToast('不支持的渠道类型', 'danger');
        return;
    }

    // 填充基本信息
    document.getElementById('editChannelId').value = channel.id;
    document.getElementById('editChannelType').value = channelType;  // 使用映射后的类型
    document.getElementById('editChannelName').value = channel.name;
    document.getElementById('editChannelEnabled').checked = channel.enabled;

    // 解析配置数据
    let configData = {};
    try {
        configData = JSON.parse(channel.config || '{}');
    } catch (e) {
        // 兼容旧格式（直接字符串）
        if (channel.type === 'dingtalk' || channel.type === 'ding_talk') {
        configData = { webhook_url: channel.config };
        } else {
        configData = { config: channel.config };
        }
    }

    // 生成编辑字段
    const fieldsContainer = document.getElementById('editChannelConfigFields');
    fieldsContainer.innerHTML = '';

    config.fields.forEach(field => {
        const fieldHtml = generateFieldHtml(field, 'edit_');
        fieldsContainer.insertAdjacentHTML('beforeend', fieldHtml);

        // 填充现有值
        const element = document.getElementById('edit_' + field.id);
        if (element && configData[field.id]) {
        element.value = configData[field.id];
        }
    });

    // 显示编辑模态框
    const modal = new bootstrap.Modal(document.getElementById('editChannelModal'));
    modal.show();
    } catch (error) {
    console.error('编辑通知渠道失败:', error);
    showToast('编辑通知渠道失败', 'danger');
    }
}

// 更新通知渠道
async function updateNotificationChannel() {
    const channelId = document.getElementById('editChannelId').value;
    const type = document.getElementById('editChannelType').value;
    const name = document.getElementById('editChannelName').value;
    const enabled = document.getElementById('editChannelEnabled').checked;

    if (!name.trim()) {
    showToast('请输入渠道名称', 'warning');
    return;
    }

    const config = channelTypeConfigs[type];
    if (!config) {
    showToast('无效的渠道类型', 'danger');
    return;
    }

    // 收集配置数据
    const configData = {};
    let hasError = false;

    config.fields.forEach(field => {
    const element = document.getElementById('edit_' + field.id);
    const value = element.value.trim();

    if (field.required && !value) {
        showToast(`请填写${field.label}`, 'warning');
        hasError = true;
        return;
    }

    if (value) {
        configData[field.id] = value;
    }
    });

    if (hasError) return;

    try {
    const response = await fetch(`${apiBase}/notification-channels/${channelId}`, {
        method: 'PUT',
        headers: {
        'Authorization': `Bearer ${authToken}`,
        'Content-Type': 'application/json'
        },
        body: JSON.stringify({
        name: name,
        config: JSON.stringify(configData),
        enabled: enabled
        })
    });

    if (response.ok) {
        showToast('通知渠道更新成功', 'success');
        const modal = bootstrap.Modal.getInstance(document.getElementById('editChannelModal'));
        modal.hide();
        loadNotificationChannels();
    } else {
        const error = await response.text();
        showToast(`更新失败: ${error}`, 'danger');
    }
    } catch (error) {
    console.error('更新通知渠道失败:', error);
    showToast('更新通知渠道失败', 'danger');
    }
}

// ================================
// 【消息通知菜单】相关功能
// ================================

// 加载消息通知配置
async function loadMessageNotifications() {
    try {
    // 获取所有账号
    const accountsResponse = await fetch(`${apiBase}/cookies`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (!accountsResponse.ok) {
        throw new Error('获取账号列表失败');
    }

    const accounts = await accountsResponse.json();

    // 获取所有通知配置
    const notificationsResponse = await fetch(`${apiBase}/message-notifications`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    let notifications = {};
    if (notificationsResponse.ok) {
        notifications = await notificationsResponse.json();
    }

    renderMessageNotifications(accounts, notifications);
    } catch (error) {
    console.error('加载消息通知配置失败:', error);
    showToast('加载消息通知配置失败', 'danger');
    }
}

// 渲染消息通知配置
function renderMessageNotifications(accounts, notifications) {
    const tbody = document.getElementById('notificationsTableBody');
    tbody.innerHTML = '';

    if (accounts.length === 0) {
    tbody.innerHTML = `
        <tr>
        <td colspan="4" class="text-center py-4 text-muted">
            <i class="bi bi-chat-dots fs-1 d-block mb-3"></i>
            <h5>暂无账号数据</h5>
            <p class="mb-0">请先添加账号</p>
        </td>
        </tr>
    `;
    return;
    }

    accounts.forEach(accountId => {
    const accountNotifications = notifications[accountId] || [];
    const tr = document.createElement('tr');

    let channelsList = '';
    if (accountNotifications.length > 0) {
        channelsList = accountNotifications.map(n =>
        `<span class="badge bg-${n.enabled ? 'success' : 'secondary'} me-1">${n.channel_name}</span>`
        ).join('');
    } else {
        channelsList = '<span class="text-muted">未配置</span>';
    }

    const status = accountNotifications.some(n => n.enabled) ?
        '<span class="badge bg-success">启用</span>' :
        '<span class="badge bg-secondary">禁用</span>';

    tr.innerHTML = `
        <td><strong class="text-primary">${accountId}</strong></td>
        <td>${channelsList}</td>
        <td>${status}</td>
        <td>
        <div class="btn-group" role="group">
            <button class="btn btn-sm btn-outline-primary" onclick="configAccountNotification('${accountId}')" title="配置">
            <i class="bi bi-gear"></i> 配置
            </button>
            ${accountNotifications.length > 0 ? `
            <button class="btn btn-sm btn-outline-danger" onclick="deleteAccountNotification('${accountId}')" title="删除配置">
            <i class="bi bi-trash"></i>
            </button>
            ` : ''}
        </div>
        </td>
    `;

    tbody.appendChild(tr);
    });
}

// 配置账号通知
async function configAccountNotification(accountId) {
    try {
    // 获取所有通知渠道
    const channelsResponse = await fetch(`${apiBase}/notification-channels`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (!channelsResponse.ok) {
        throw new Error('获取通知渠道失败');
    }

    const channels = await channelsResponse.json();

    if (channels.length === 0) {
        showToast('请先添加通知渠道', 'warning');
        return;
    }

    // 获取当前账号的通知配置
    const notificationResponse = await fetch(`${apiBase}/message-notifications/${accountId}`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    let currentNotifications = [];
    if (notificationResponse.ok) {
        currentNotifications = await notificationResponse.json();
    }

    // 填充表单
    document.getElementById('configAccountId').value = accountId;
    document.getElementById('displayAccountId').value = accountId;

    // 填充通知渠道选项
    const channelSelect = document.getElementById('notificationChannel');
    channelSelect.innerHTML = '<option value="">请选择通知渠道</option>';

    // 获取当前配置的第一个通知渠道（如果存在）
    const currentNotification = currentNotifications.length > 0 ? currentNotifications[0] : null;

    channels.forEach(channel => {
        if (channel.enabled) {
        const option = document.createElement('option');
        option.value = channel.id;
        option.textContent = `${channel.name} (${channel.config})`;
        if (currentNotification && currentNotification.channel_id === channel.id) {
            option.selected = true;
        }
        channelSelect.appendChild(option);
        }
    });

    // 设置启用状态
    document.getElementById('notificationEnabled').checked =
        currentNotification ? currentNotification.enabled : true;

    // 显示配置模态框
    const modal = new bootstrap.Modal(document.getElementById('configNotificationModal'));
    modal.show();
    } catch (error) {
    console.error('配置账号通知失败:', error);
    showToast('配置账号通知失败', 'danger');
    }
}

// 删除账号通知配置
async function deleteAccountNotification(accountId) {
    if (!confirm(`确定要删除账号 ${accountId} 的通知配置吗？`)) {
    return;
    }

    try {
    const response = await fetch(`${apiBase}/message-notifications/account/${accountId}`, {
        method: 'DELETE',
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        showToast('通知配置删除成功', 'success');
        loadMessageNotifications();
    } else {
        const error = await response.text();
        showToast(`删除失败: ${error}`, 'danger');
    }
    } catch (error) {
    console.error('删除通知配置失败:', error);
    showToast('删除通知配置失败', 'danger');
    }
}

// 保存账号通知配置
async function saveAccountNotification() {
    const accountId = document.getElementById('configAccountId').value;
    const channelId = document.getElementById('notificationChannel').value;
    const enabled = document.getElementById('notificationEnabled').checked;

    if (!channelId) {
    showToast('请选择通知渠道', 'warning');
    return;
    }

    try {
    const response = await fetch(`${apiBase}/message-notifications/${accountId}`, {
        method: 'POST',
        headers: {
        'Authorization': `Bearer ${authToken}`,
        'Content-Type': 'application/json'
        },
        body: JSON.stringify({
        channel_id: parseInt(channelId),
        enabled: enabled
        })
    });

    if (response.ok) {
        showToast('通知配置保存成功', 'success');
        const modal = bootstrap.Modal.getInstance(document.getElementById('configNotificationModal'));
        modal.hide();
        loadMessageNotifications();
    } else {
        const error = await response.text();
        showToast(`保存失败: ${error}`, 'danger');
    }
    } catch (error) {
    console.error('保存通知配置失败:', error);
    showToast('保存通知配置失败', 'danger');
    }
}

// ================================
// 【卡种管理菜单】相关功能
// ================================

// 加载卡券列表
async function loadCards() {
    try {
    const response = await fetch(`${apiBase}/cards`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        const cards = await response.json();
        renderCardsList(cards);
        updateCardsStats(cards);
    } else {
        showToast('加载卡券列表失败', 'danger');
    }
    } catch (error) {
    console.error('加载卡券列表失败:', error);
    showToast('加载卡券列表失败', 'danger');
    }
}

// 渲染卡券列表
function renderCardsList(cards) {
    const tbody = document.getElementById('cardsTableBody');

    if (cards.length === 0) {
    tbody.innerHTML = `
        <tr>
        <td colspan="8" class="text-center py-4 text-muted">
            <i class="bi bi-credit-card fs-1 d-block mb-3"></i>
            <h5>暂无卡券数据</h5>
            <p class="mb-0">点击"添加卡券"开始创建您的第一个卡券</p>
        </td>
        </tr>
    `;
    return;
    }

    tbody.innerHTML = '';

    cards.forEach(card => {
    const tr = document.createElement('tr');

    // 类型标签
    let typeBadge = '';
    switch(card.type) {
        case 'api':
        typeBadge = '<span class="badge bg-info">API接口</span>';
        break;
        case 'text':
        typeBadge = '<span class="badge bg-success">固定文字</span>';
        break;
        case 'data':
        typeBadge = '<span class="badge bg-warning">批量数据</span>';
        break;
        case 'image':
        typeBadge = '<span class="badge bg-primary">图片</span>';
        break;
    }

    // 状态标签
    const statusBadge = card.enabled ?
        '<span class="badge bg-success">启用</span>' :
        '<span class="badge bg-secondary">禁用</span>';

    // 数据量显示
    let dataCount = '-';
    if (card.type === 'data' && card.data_content) {
        const lines = card.data_content.split('\n').filter(line => line.trim());
        dataCount = lines.length;
    } else if (card.type === 'api') {
        dataCount = '∞';
    } else if (card.type === 'text') {
        dataCount = '1';
    } else if (card.type === 'image') {
        dataCount = '1';
    }

    // 延时时间显示
    const delayDisplay = card.delay_seconds > 0 ?
        `${card.delay_seconds}秒` :
        '<span class="text-muted">立即</span>';

    // 规格信息显示 - 卡券不再有多规格功能
    let specDisplay = '<span class="text-muted">普通卡券</span>';

    tr.innerHTML = `
        <td>
        <div class="fw-bold">${card.name}</div>
        ${card.description ? `<small class="text-muted">${card.description}</small>` : ''}
        </td>
        <td>${typeBadge}</td>
        <td>${specDisplay}</td>
        <td>${dataCount}</td>
        <td>${delayDisplay}</td>
        <td>${statusBadge}</td>
        <td>
        <small class="text-muted">${new Date(card.created_at).toLocaleString('zh-CN')}</small>
        </td>
        <td>
        <div class="btn-group" role="group">
            <button class="btn btn-sm btn-outline-primary" onclick="editCard(${card.id})" title="编辑">
            <i class="bi bi-pencil"></i>
            </button>
            <button class="btn btn-sm btn-outline-info" onclick="testCard(${card.id})" title="测试">
            <i class="bi bi-play"></i>
            </button>
            <button class="btn btn-sm btn-outline-danger" onclick="deleteCard(${card.id})" title="删除">
            <i class="bi bi-trash"></i>
            </button>
        </div>
        </td>
    `;

    tbody.appendChild(tr);
    });
}

// 更新卡券统计
function updateCardsStats(cards) {
    const totalCards = cards.length;
    const apiCards = cards.filter(card => card.type === 'api').length;
    const textCards = cards.filter(card => card.type === 'text').length;
    const dataCards = cards.filter(card => card.type === 'data').length;

    document.getElementById('totalCards').textContent = totalCards;
    document.getElementById('apiCards').textContent = apiCards;
    document.getElementById('textCards').textContent = textCards;
    document.getElementById('dataCards').textContent = dataCards;
}

// 显示添加卡券模态框
function showAddCardModal() {
    document.getElementById('addCardForm').reset();
    toggleCardTypeFields();
    const modal = new bootstrap.Modal(document.getElementById('addCardModal'));
    modal.show();
}

// 切换卡券类型字段显示
function toggleCardTypeFields() {
    const cardType = document.getElementById('cardType').value;

    document.getElementById('apiFields').style.display = cardType === 'api' ? 'block' : 'none';
    document.getElementById('textFields').style.display = cardType === 'text' ? 'block' : 'none';
    document.getElementById('dataFields').style.display = cardType === 'data' ? 'block' : 'none';
    document.getElementById('imageFields').style.display = cardType === 'image' ? 'block' : 'none';
    
    // 只有批量数据类型的卡券才显示库存预警字段
    document.getElementById('stockWarningField').style.display = cardType === 'data' ? 'block' : 'none';
}



// 切换发货规则多规格字段显示
function toggleRuleMultiSpecFields() {
    const isMultiSpec = document.getElementById('ruleIsMultiSpec').checked;
    document.getElementById('ruleMultiSpecFields').style.display = isMultiSpec ? 'block' : 'none';
}

// 切换编辑发货规则多规格字段显示
function toggleEditRuleMultiSpecFields() {
    const isMultiSpec = document.getElementById('editRuleIsMultiSpec').checked;
    document.getElementById('editRuleMultiSpecFields').style.display = isMultiSpec ? 'block' : 'none';
}

// 初始化卡券图片文件选择器
function initCardImageFileSelector() {
    const fileInput = document.getElementById('cardImageFile');
    if (fileInput) {
        fileInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                // 验证文件类型
                if (!file.type.startsWith('image/')) {
                    showToast('❌ 请选择图片文件，当前文件类型：' + file.type, 'warning');
                    e.target.value = '';
                    hideCardImagePreview();
                    return;
                }

                // 验证文件大小（5MB）
                if (file.size > 5 * 1024 * 1024) {
                    showToast('❌ 图片文件大小不能超过 5MB，当前文件大小：' + (file.size / 1024 / 1024).toFixed(1) + 'MB', 'warning');
                    e.target.value = '';
                    hideCardImagePreview();
                    return;
                }

                // 验证图片尺寸
                validateCardImageDimensions(file, e.target);
            } else {
                hideCardImagePreview();
            }
        });
    }
}

// 验证卡券图片尺寸
function validateCardImageDimensions(file, inputElement) {
    const img = new Image();
    const url = URL.createObjectURL(file);

    img.onload = function() {
        const width = this.naturalWidth;
        const height = this.naturalHeight;

        // 释放对象URL
        URL.revokeObjectURL(url);

        // 检查图片尺寸
        const maxDimension = 4096;
        const maxPixels = 8 * 1024 * 1024; // 8M像素
        const totalPixels = width * height;

        if (width > maxDimension || height > maxDimension) {
            showToast(`❌ 图片尺寸过大：${width}x${height}，最大允许：${maxDimension}x${maxDimension}像素`, 'warning');
            inputElement.value = '';
            hideCardImagePreview();
            return;
        }

        if (totalPixels > maxPixels) {
            showToast(`❌ 图片像素总数过大：${(totalPixels / 1024 / 1024).toFixed(1)}M像素，最大允许：8M像素`, 'warning');
            inputElement.value = '';
            hideCardImagePreview();
            return;
        }

        // 尺寸检查通过，显示预览和提示信息
        showCardImagePreview(file);

        // 如果图片较大，提示会被压缩
        if (width > 2048 || height > 2048) {
            showToast(`ℹ️ 图片尺寸较大（${width}x${height}），上传时将自动压缩以优化性能`, 'info');
        } else {
            showToast(`✅ 图片尺寸合适（${width}x${height}），可以上传`, 'success');
        }
    };

    img.onerror = function() {
        URL.revokeObjectURL(url);
        showToast('❌ 无法读取图片文件，请选择有效的图片', 'warning');
        inputElement.value = '';
        hideCardImagePreview();
    };

    img.src = url;
}

// 显示卡券图片预览
function showCardImagePreview(file) {
    const reader = new FileReader();
    reader.onload = function(e) {
        const previewContainer = document.getElementById('cardImagePreview');
        const previewImg = document.getElementById('cardPreviewImg');

        previewImg.src = e.target.result;
        previewContainer.style.display = 'block';
    };
    reader.readAsDataURL(file);
}

// 隐藏卡券图片预览
function hideCardImagePreview() {
    const previewContainer = document.getElementById('cardImagePreview');
    if (previewContainer) {
        previewContainer.style.display = 'none';
    }
}

// 初始化编辑卡券图片文件选择器
function initEditCardImageFileSelector() {
    const fileInput = document.getElementById('editCardImageFile');
    if (fileInput) {
        fileInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                // 验证文件类型
                if (!file.type.startsWith('image/')) {
                    showToast('❌ 请选择图片文件，当前文件类型：' + file.type, 'warning');
                    e.target.value = '';
                    hideEditCardImagePreview();
                    return;
                }

                // 验证文件大小（5MB）
                if (file.size > 5 * 1024 * 1024) {
                    showToast('❌ 图片文件大小不能超过 5MB，当前文件大小：' + (file.size / 1024 / 1024).toFixed(1) + 'MB', 'warning');
                    e.target.value = '';
                    hideEditCardImagePreview();
                    return;
                }

                // 验证图片尺寸
                validateEditCardImageDimensions(file, e.target);
            } else {
                hideEditCardImagePreview();
            }
        });
    }
}

// 验证编辑卡券图片尺寸
function validateEditCardImageDimensions(file, inputElement) {
    const img = new Image();
    const url = URL.createObjectURL(file);

    img.onload = function() {
        const width = this.naturalWidth;
        const height = this.naturalHeight;

        URL.revokeObjectURL(url);

        // 检查尺寸限制
        if (width > 4096 || height > 4096) {
            showToast(`❌ 图片尺寸过大（${width}x${height}），最大支持 4096x4096 像素`, 'warning');
            inputElement.value = '';
            hideEditCardImagePreview();
            return;
        }

        // 显示图片预览
        showEditCardImagePreview(file);

        // 如果图片较大，提示会被压缩
        if (width > 2048 || height > 2048) {
            showToast(`ℹ️ 图片尺寸较大（${width}x${height}），上传时将自动压缩以优化性能`, 'info');
        } else {
            showToast(`✅ 图片尺寸合适（${width}x${height}），可以上传`, 'success');
        }
    };

    img.onerror = function() {
        URL.revokeObjectURL(url);
        showToast('❌ 无法读取图片文件，请选择有效的图片', 'warning');
        inputElement.value = '';
        hideEditCardImagePreview();
    };

    img.src = url;
}

// 显示编辑卡券图片预览
function showEditCardImagePreview(file) {
    const reader = new FileReader();
    reader.onload = function(e) {
        const previewImg = document.getElementById('editCardPreviewImg');
        const previewContainer = document.getElementById('editCardImagePreview');

        if (previewImg && previewContainer) {
            previewImg.src = e.target.result;
            previewContainer.style.display = 'block';
        }
    };
    reader.readAsDataURL(file);
}

// 隐藏编辑卡券图片预览
function hideEditCardImagePreview() {
    const previewContainer = document.getElementById('editCardImagePreview');
    if (previewContainer) {
        previewContainer.style.display = 'none';
    }
}



// 清空添加卡券表单
function clearAddCardForm() {
    try {
    // 安全地清空表单字段
    const setElementValue = (id, value) => {
        const element = document.getElementById(id);
        if (element) {
        if (element.type === 'checkbox') {
            element.checked = value;
        } else {
            element.value = value;
        }
        } else {
        console.warn(`Element with id '${id}' not found`);
        }
    };

    const setElementDisplay = (id, display) => {
        const element = document.getElementById(id);
        if (element) {
        element.style.display = display;
        } else {
        console.warn(`Element with id '${id}' not found`);
        }
    };

    // 清空基本字段
    setElementValue('cardName', '');
    setElementValue('cardType', 'text');
    setElementValue('cardDescription', '');
    setElementValue('cardDelaySeconds', '0');
    setElementValue('isMultiSpec', false);
    setElementValue('specName', '');
    setElementValue('specValue', '');

    // 隐藏多规格字段
    setElementDisplay('multiSpecFields', 'none');

    // 清空类型相关字段
    setElementValue('textContent', '');
    setElementValue('dataContent', '');
    setElementValue('apiCouponSeedId', '');
    setElementValue('apiCompanysk', '');
    setElementValue('apiUrl', '');
    setElementValue('apiMethod', 'GET');
    setElementValue('apiHeaders', '');
    setElementValue('apiParams', '');
    setElementValue('apiTimeout', '10');

    // 重置字段显示
    toggleCardTypeFields();
    } catch (error) {
    console.error('清空表单时出错:', error);
    }
}

// 保存卡券
async function saveCard() {
    try {
    const cardType = document.getElementById('cardType').value;
    const cardName = document.getElementById('cardName').value;

    if (!cardType || !cardName) {
        showToast('请填写必填字段', 'warning');
        return;
    }

    const cardData = {
        name: cardName,
        type: cardType,
        description: document.getElementById('cardDescription').value,
        delay_seconds: parseInt(document.getElementById('cardDelaySeconds').value) || 0,
        enabled: true,
        stock_warning_threshold: cardType === 'data' ? (parseInt(document.getElementById('stockWarningThreshold').value) || 0) : 0
    };

    // 根据类型添加特定配置
    switch(cardType) {
        case 'api':
        // 验证卡种ID和公司SK
        const couponSeedId = document.getElementById('apiCouponSeedId').value;
        const companysk = document.getElementById('apiCompanysk').value;
        
        if (!couponSeedId || !companysk) {
            showToast('请填写卡种ID和公司SK', 'warning');
            return;
        }

        cardData.api_config = {
            couponSeedId: parseInt(couponSeedId),
            companysk: companysk
        };
        break;
        case 'text':
        cardData.text_content = document.getElementById('textContent').value;
        break;
        case 'data':
        cardData.data_content = document.getElementById('dataContent').value;
        break;
        case 'image':
        // 处理图片上传
        const imageFile = document.getElementById('cardImageFile').files[0];
        if (!imageFile) {
            showToast('请选择图片文件', 'warning');
            return;
        }

        // 上传图片
        const formData = new FormData();
        formData.append('image', imageFile);

        const uploadResponse = await fetch(`${apiBase}/upload-image`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${authToken}`
            },
            body: formData
        });

        if (!uploadResponse.ok) {
            const errorData = await uploadResponse.json();
            showToast(`图片上传失败: ${errorData.detail || '未知错误'}`, 'danger');
            return;
        }

        const uploadResult = await uploadResponse.json();
        cardData.image_url = uploadResult.image_url;
        break;
    }

    const response = await fetch(`${apiBase}/cards`, {
        method: 'POST',
        headers: {
        'Authorization': `Bearer ${authToken}`,
        'Content-Type': 'application/json'
        },
        body: JSON.stringify(cardData)
    });

    if (response.ok) {
        showToast('卡券保存成功', 'success');
        bootstrap.Modal.getInstance(document.getElementById('addCardModal')).hide();
        // 清空表单
        clearAddCardForm();
        loadCards();
    } else {
        let errorMessage = '保存失败';
        try {
        const errorData = await response.json();
        errorMessage = errorData.error || errorData.detail || errorMessage;
        } catch (e) {
        // 如果不是JSON格式，尝试获取文本
        try {
            const errorText = await response.text();
            errorMessage = errorText || errorMessage;
        } catch (e2) {
            errorMessage = `HTTP ${response.status}: ${response.statusText}`;
        }
        }
        showToast(`保存失败: ${errorMessage}`, 'danger');
    }
    } catch (error) {
    console.error('保存卡券失败:', error);
    showToast(`网络错误: ${error.message}`, 'danger');
    }
}
// ================================
// 【自动发货菜单】相关功能
// ================================

// 加载发货规则列表
async function loadDeliveryRules() {
    console.log('loadDeliveryRules called');
    try {
    const response = await fetch(`${apiBase}/delivery-rules`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        const rules = await response.json();
        console.log('Received', rules.length, 'delivery rules from API');
        
        // 更新全局变量，用于详情显示
        currentDeliveryRules = rules;
        
        renderDeliveryRulesList(rules);
        updateDeliveryStats(rules);

        // 同时加载卡券列表用于下拉选择
        loadCardsForSelect();
    } else {
        showToast('加载发货规则失败', 'danger');
    }
    } catch (error) {
    console.error('加载发货规则失败:', error);
    showToast('加载发货规则失败', 'danger');
    }
}

// 渲染发货规则列表
function renderDeliveryRulesList(rules) {
    console.log('renderDeliveryRulesList called with', rules.length, 'rules');
    const tbody = document.getElementById('deliveryRulesTableBody');

    if (rules.length === 0) {
    tbody.innerHTML = `
        <tr>
        <td colspan="7" class="text-center py-4 text-muted">
            <i class="bi bi-truck fs-1 d-block mb-3"></i>
            <h5>暂无发货规则</h5>
            <p class="mb-0">点击"添加规则"开始配置自动发货规则</p>
        </td>
        </tr>
    `;
    return;
    }

    console.log('Clearing tbody and rendering', rules.length, 'rules');
    // 强制清空表格内容
    while (tbody.firstChild) {
        tbody.removeChild(tbody.firstChild);
    }

    // 直接渲染每条规则，不进行分组，确保每个商品ID对应一条记录
    rules.forEach(rule => {
        const tr = document.createElement('tr');
        
        // 卡券类型标签
        let cardTypeBadge = '<span class="badge bg-secondary">未知</span>';
        if (rule.card_type) {
            switch(rule.card_type) {
            case 'api':
                cardTypeBadge = '<span class="badge bg-info">API接口</span>';
                break;
            case 'text':
                cardTypeBadge = '<span class="badge bg-success">固定文字</span>';
                break;
            case 'data':
                cardTypeBadge = '<span class="badge bg-warning">批量数据</span>';
                break;
            case 'image':
                cardTypeBadge = '<span class="badge bg-primary">图片</span>';
                break;
            }
        }

        // 状态标签
        const statusBadge = rule.enabled ?
            '<span class="badge bg-success">启用</span>' :
            '<span class="badge bg-secondary">禁用</span>';
            
        // 图片生成标签
        const generateImageBadge = rule.generate_image !== false ?
            '<span class="badge bg-success"><i class="bi bi-image"></i> 是</span>' :
            '<span class="badge bg-secondary"><i class="bi bi-file-text"></i> 否</span>';

        tr.innerHTML = `
            <td>
                <div class="fw-bold">${rule.item_id}</div>
                ${rule.item_title ? `<small class="text-muted">${rule.item_title}</small>` : ''}
            </td>
            <td>
                <div>
                    <span class="badge bg-primary">${rule.card_name || '未知卡券'}</span>
                    ${rule.is_multi_spec && rule.spec_name && rule.spec_value ?
                        `<br><small class="text-muted mt-1 d-block"><i class="bi bi-tags"></i> ${rule.spec_name}: ${rule.spec_value}</small>` :
                        ''}
                </div>
            </td>
            <td>${cardTypeBadge}</td>
            <td>
                <span class="badge bg-info">${rule.delivery_count || 1}</span>
            </td>
            <td>${statusBadge}</td>
            <td>${generateImageBadge}</td>
            <td>
                <span class="badge bg-warning">${rule.delivery_times || 0}</span>
            </td>
            <td>
                <div class="btn-group" role="group">
                    <button class="btn btn-sm btn-outline-primary" onclick="editDeliveryRule(${rule.id})" title="编辑">
                        <i class="bi bi-pencil"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-info" onclick="testDeliveryRule(${rule.id})" title="测试">
                        <i class="bi bi-play"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-danger" onclick="deleteDeliveryRule(${rule.id})" title="删除">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </td>
        `;

        tbody.appendChild(tr);
        console.log('Added rule row for ID:', rule.id, 'Item ID:', rule.item_id, 'Total rows now:', tbody.children.length);
    });
}

// 更新发货统计
function updateDeliveryStats(rules) {
    const totalRules = rules.length;
    const activeRules = rules.filter(rule => rule.enabled).length;
    const todayDeliveries = 0; // 需要从后端获取今日发货统计
    const totalDeliveries = rules.reduce((sum, rule) => sum + (rule.delivery_times || 0), 0);

    document.getElementById('totalRules').textContent = totalRules;
    document.getElementById('activeRules').textContent = activeRules;
    document.getElementById('todayDeliveries').textContent = todayDeliveries;
    document.getElementById('totalDeliveries').textContent = totalDeliveries;
}

// 显示添加发货规则模态框
function showAddDeliveryRuleModal() {
    document.getElementById('addDeliveryRuleForm').reset();
    
    // 重置多规格字段
    document.getElementById('ruleIsMultiSpec').checked = false;
    document.getElementById('ruleSpecName').value = '';
    document.getElementById('ruleSpecValue').value = '';
    document.getElementById('ruleMultiSpecFields').style.display = 'none';
    
    loadCardsForSelect(); // 加载卡券选项
    const modal = new bootstrap.Modal(document.getElementById('addDeliveryRuleModal'));
    modal.show();
}

// 加载卡券列表用于下拉选择
async function loadCardsForSelect() {
    try {
    const response = await fetch(`${apiBase}/cards`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        const cards = await response.json();
        const select = document.getElementById('selectedCard');

        // 清空现有选项
        select.innerHTML = '<option value="">请选择卡券</option>';

        cards.forEach(card => {
        if (card.enabled) { // 只显示启用的卡券
            const option = document.createElement('option');
            option.value = card.id;

            // 构建显示文本
            let displayText = card.name;

            // 添加类型信息
            let typeText;
            switch(card.type) {
                case 'api':
                    typeText = 'API';
                    break;
                case 'text':
                    typeText = '固定文字';
                    break;
                case 'data':
                    typeText = '批量数据';
                    break;
                case 'image':
                    typeText = '图片';
                    break;
                default:
                    typeText = '未知类型';
            }
            displayText += ` (${typeText})`;

            option.textContent = displayText;
            select.appendChild(option);
        }
        });
    }
    } catch (error) {
    console.error('加载卡券选项失败:', error);
    }
}



// 保存发货规则
async function saveDeliveryRule() {
    try {
    const itemId = document.getElementById('productItemId').value.trim();
    const cardId = document.getElementById('selectedCard').value;
    const deliveryCount = document.getElementById('deliveryCount').value;
    const enabled = document.getElementById('ruleEnabled').checked;
    const description = document.getElementById('ruleDescription').value;

    if (!itemId || !cardId) {
        showToast('请填写必填字段', 'warning');
        return;
    }

    // 验证商品ID格式，支持换行和逗号分割
    const itemIds = [];
    for (const line of itemId.split('\n')) {
        const trimmedLine = line.trim();
        if (trimmedLine) {
            // 每行可能包含逗号分隔的多个ID
            const lineIds = trimmedLine.split(',').map(id => id.trim()).filter(id => id);
            itemIds.push(...lineIds);
        }
    }
    
    // 去重并保持顺序
    const uniqueItemIds = [...new Set(itemIds)];
    
    if (uniqueItemIds.length === 0) {
        showToast('请输入有效的商品ID', 'warning');
        return;
    }

    // 验证每个商品ID是否为有效格式（可以根据需要调整验证规则）
    const invalidIds = uniqueItemIds.filter(id => !/^\d+$/.test(id));
    if (invalidIds.length > 0) {
        showToast(`商品ID格式不正确: ${invalidIds.join(', ')}`, 'warning');
        return;
    }

    const generateImage = document.getElementById('generateImage').checked;

    // 检查多规格设置
    const isMultiSpec = document.getElementById('ruleIsMultiSpec').checked;
    const specName = document.getElementById('ruleSpecName').value;
    const specValue = document.getElementById('ruleSpecValue').value;

    // 验证多规格字段
    if (isMultiSpec && (!specName || !specValue)) {
        showToast('多规格发货规则必须填写规格名称和规格值', 'warning');
        return;
    }

    const ruleData = {
        item_id: itemId, // 保持原始输入格式，后端会处理分割
        card_id: parseInt(cardId),
        delivery_count: parseInt(deliveryCount),
        enabled: enabled,
        description: description,
        generate_image: generateImage,
        is_multi_spec: isMultiSpec,
        spec_name: isMultiSpec ? specName : null,
        spec_value: isMultiSpec ? specValue : null
    };

    const response = await fetch(`${apiBase}/delivery-rules`, {
        method: 'POST',
        headers: {
        'Authorization': `Bearer ${authToken}`,
        'Content-Type': 'application/json'
        },
        body: JSON.stringify(ruleData)
    });

    if (response.ok) {
        const result = await response.json();
        if (result.created_count > 0) {
            showToast(`成功创建 ${result.created_count} 条发货规则`, 'success');
        } else {
            showToast(result.message || '发货规则保存成功', 'info');
        }
        bootstrap.Modal.getInstance(document.getElementById('addDeliveryRuleModal')).hide();
        console.log('Delivery rule saved successfully, calling loadDeliveryRules');
        loadDeliveryRules();
    } else {
        const error = await response.text();
        showToast(`保存失败: ${error}`, 'danger');
    }
    } catch (error) {
    console.error('保存发货规则失败:', error);
    showToast('保存发货规则失败', 'danger');
    }
}

// 编辑卡券
async function editCard(cardId) {
    try {
    // 获取卡券详情
    const response = await fetch(`${apiBase}/cards/${cardId}`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        const card = await response.json();

        // 填充编辑表单
        document.getElementById('editCardId').value = card.id;
        document.getElementById('editCardName').value = card.name;
        document.getElementById('editCardType').value = card.type;
        document.getElementById('editCardDescription').value = card.description || '';
        document.getElementById('editCardDelaySeconds').value = card.delay_seconds || 0;
        document.getElementById('editCardEnabled').checked = card.enabled;

        // 填充库存预警阈值
        document.getElementById('editStockWarningThreshold').value = card.stock_warning_threshold || 0;

        // 根据类型填充特定字段
        if (card.type === 'api' && card.api_config) {
        document.getElementById('editApiCouponSeedId').value = card.api_config.couponSeedId || '';
        // 兼容性处理：优先使用companysk，如果没有则使用旧的companyId
        document.getElementById('editApiCompanysk').value = card.api_config.companysk || card.api_config.companyId || '';
        } else if (card.type === 'text') {
        document.getElementById('editTextContent').value = card.text_content || '';
        } else if (card.type === 'data') {
        document.getElementById('editDataContent').value = card.data_content || '';
        } else if (card.type === 'image') {
        // 处理图片类型
        const currentImagePreview = document.getElementById('editCurrentImagePreview');
        const currentImg = document.getElementById('editCurrentImg');
        const noImageText = document.getElementById('editNoImageText');

        if (card.image_url) {
            // 显示当前图片
            currentImg.src = card.image_url;
            currentImagePreview.style.display = 'block';
            noImageText.style.display = 'none';
        } else {
            // 没有图片
            currentImagePreview.style.display = 'none';
            noImageText.style.display = 'block';
        }

        // 清空文件选择器和预览
        document.getElementById('editCardImageFile').value = '';
        document.getElementById('editCardImagePreview').style.display = 'none';
        }

        // 显示对应的字段
        toggleEditCardTypeFields();



        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('editCardModal'));
        modal.show();
    } else {
        showToast('获取卡券详情失败', 'danger');
    }
    } catch (error) {
    console.error('获取卡券详情失败:', error);
    showToast('获取卡券详情失败', 'danger');
    }
}

// 切换编辑卡券类型字段显示
function toggleEditCardTypeFields() {
    const cardType = document.getElementById('editCardType').value;

    document.getElementById('editApiFields').style.display = cardType === 'api' ? 'block' : 'none';
    document.getElementById('editTextFields').style.display = cardType === 'text' ? 'block' : 'none';
    document.getElementById('editDataFields').style.display = cardType === 'data' ? 'block' : 'none';
    document.getElementById('editImageFields').style.display = cardType === 'image' ? 'block' : 'none';
    
    // 只有批量数据类型的卡券才显示库存预警字段
    document.getElementById('editStockWarningField').style.display = cardType === 'data' ? 'block' : 'none';
}

// 更新卡券
async function updateCard() {
    try {
    const cardId = document.getElementById('editCardId').value;
    const cardType = document.getElementById('editCardType').value;
    const cardName = document.getElementById('editCardName').value;

    if (!cardType || !cardName) {
        showToast('请填写必填字段', 'warning');
        return;
    }

    const cardData = {
        name: cardName,
        type: cardType,
        description: document.getElementById('editCardDescription').value,
        delay_seconds: parseInt(document.getElementById('editCardDelaySeconds').value) || 0,
        enabled: document.getElementById('editCardEnabled').checked,
        stock_warning_threshold: cardType === 'data' ? (parseInt(document.getElementById('editStockWarningThreshold').value) || 0) : 0
    };

    // 根据类型添加特定配置
    switch(cardType) {
        case 'api':
        // 验证卡种ID和公司SK
        const editCouponSeedId = document.getElementById('editApiCouponSeedId').value;
        const editCompanysk = document.getElementById('editApiCompanysk').value;
        
        if (!editCouponSeedId || !editCompanysk) {
            showToast('请填写卡种ID和公司SK', 'warning');
            return;
        }

        cardData.api_config = {
            couponSeedId: parseInt(editCouponSeedId),
            companysk: editCompanysk
        };
        break;
        case 'text':
        cardData.text_content = document.getElementById('editTextContent').value;
        break;
        case 'data':
        cardData.data_content = document.getElementById('editDataContent').value;
        break;
        case 'image':
        // 处理图片类型 - 如果有新图片则上传，否则保持原有图片
        const imageFile = document.getElementById('editCardImageFile').files[0];
        if (imageFile) {
            // 有新图片，需要上传
            await updateCardWithImage(cardId, cardData, imageFile);
            return; // 提前返回，因为上传图片是异步的
        }
        // 没有新图片，保持原有配置，继续正常更新流程
        break;
    }

    const response = await fetch(`${apiBase}/cards/${cardId}`, {
        method: 'PUT',
        headers: {
        'Authorization': `Bearer ${authToken}`,
        'Content-Type': 'application/json'
        },
        body: JSON.stringify(cardData)
    });

    if (response.ok) {
        showToast('卡券更新成功', 'success');
        bootstrap.Modal.getInstance(document.getElementById('editCardModal')).hide();
        loadCards();
    } else {
        const error = await response.text();
        showToast(`更新失败: ${error}`, 'danger');
    }
    } catch (error) {
    console.error('更新卡券失败:', error);
    showToast('更新卡券失败', 'danger');
    }
}

// 更新带图片的卡券
async function updateCardWithImage(cardId, cardData, imageFile) {
    try {
        // 创建FormData对象
        const formData = new FormData();

        // 添加图片文件
        formData.append('image', imageFile);

        // 添加卡券数据
        Object.keys(cardData).forEach(key => {
            if (cardData[key] !== null && cardData[key] !== undefined) {
                if (typeof cardData[key] === 'object') {
                    formData.append(key, JSON.stringify(cardData[key]));
                } else {
                    formData.append(key, cardData[key]);
                }
            }
        });

        const response = await fetch(`${apiBase}/cards/${cardId}/image`, {
            method: 'PUT',
            headers: {
                'Authorization': `Bearer ${authToken}`
                // 不设置Content-Type，让浏览器自动设置multipart/form-data
            },
            body: formData
        });

        if (response.ok) {
            showToast('卡券更新成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('editCardModal')).hide();
            loadCards();
        } else {
            const error = await response.text();
            showToast(`更新失败: ${error}`, 'danger');
        }
    } catch (error) {
        console.error('更新带图片的卡券失败:', error);
        showToast('更新卡券失败', 'danger');
    }
}



// 测试卡券（占位函数）
function testCard(cardId) {
    showToast('测试功能开发中...', 'info');
}

// 删除卡券
async function deleteCard(cardId) {
    if (confirm('确定要删除这个卡券吗？删除后无法恢复！')) {
    try {
        const response = await fetch(`${apiBase}/cards/${cardId}`, {
        method: 'DELETE',
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
        });

        if (response.ok) {
        showToast('卡券删除成功', 'success');
        loadCards();
        } else {
        const error = await response.text();
        showToast(`删除失败: ${error}`, 'danger');
        }
    } catch (error) {
        console.error('删除卡券失败:', error);
        showToast('删除卡券失败', 'danger');
    }
    }
}

// 编辑发货规则
async function editDeliveryRule(ruleId) {
    try {
    // 获取发货规则详情
    const response = await fetch(`${apiBase}/delivery-rules/${ruleId}`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        const rule = await response.json();

        // 填充编辑表单
        document.getElementById('editRuleId').value = rule.id;
        document.getElementById('editDeliveryCount').value = rule.delivery_count || 1;
        document.getElementById('editRuleEnabled').checked = rule.enabled;
        document.getElementById('editGenerateImage').checked = rule.generate_image !== false;
        document.getElementById('editRuleDescription').value = rule.description || '';

        // 填充多规格字段
        const isMultiSpec = rule.is_multi_spec || false;
        document.getElementById('editRuleIsMultiSpec').checked = isMultiSpec;
        document.getElementById('editRuleSpecName').value = rule.spec_name || '';
        document.getElementById('editRuleSpecValue').value = rule.spec_value || '';
        
        // 显示/隐藏多规格字段
        toggleEditRuleMultiSpecFields();

        // 加载卡券选项
        await loadCardsForEditSelect();
        
        // 设置当前选中的商品和卡券
        document.getElementById('editProductItemId').value = rule.item_id;
        document.getElementById('editSelectedCard').value = rule.card_id;

        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('editDeliveryRuleModal'));
        modal.show();
    } else {
        showToast('获取发货规则详情失败', 'danger');
    }
    } catch (error) {
    console.error('获取发货规则详情失败:', error);
    showToast('获取发货规则详情失败', 'danger');
    }
}

// 加载卡券列表用于编辑时的下拉选择
async function loadCardsForEditSelect() {
    try {
    const response = await fetch(`${apiBase}/cards`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        const cards = await response.json();
        const select = document.getElementById('editSelectedCard');

        // 清空现有选项
        select.innerHTML = '<option value="">请选择卡券</option>';

        cards.forEach(card => {
        if (card.enabled) { // 只显示启用的卡券
            const option = document.createElement('option');
            option.value = card.id;

            // 构建显示文本
            let displayText = card.name;

            // 添加类型信息
            let typeText;
            switch(card.type) {
                case 'api':
                    typeText = 'API';
                    break;
                case 'text':
                    typeText = '固定文字';
                    break;
                case 'data':
                    typeText = '批量数据';
                    break;
                case 'image':
                    typeText = '图片';
                    break;
                default:
                    typeText = '未知类型';
            }
            displayText += ` (${typeText})`;

            option.textContent = displayText;
            select.appendChild(option);
        }
        });
    }
    } catch (error) {
    console.error('加载卡券选项失败:', error);
    }
}

// 更新发货规则
async function updateDeliveryRule() {
    try {
    const ruleId = document.getElementById('editRuleId').value;
    const itemId = document.getElementById('editProductItemId').value;
    const cardId = document.getElementById('editSelectedCard').value;
    const deliveryCount = document.getElementById('editDeliveryCount').value;
    const enabled = document.getElementById('editRuleEnabled').checked;
    const description = document.getElementById('editRuleDescription').value;

    if (!itemId || !cardId) {
        showToast('请填写必填字段', 'warning');
        return;
    }

    const generateImage = document.getElementById('editGenerateImage').checked;

    // 检查多规格设置
    const isMultiSpec = document.getElementById('editRuleIsMultiSpec').checked;
    const specName = document.getElementById('editRuleSpecName').value;
    const specValue = document.getElementById('editRuleSpecValue').value;

    // 验证多规格字段
    if (isMultiSpec && (!specName || !specValue)) {
        showToast('多规格发货规则必须填写规格名称和规格值', 'warning');
        return;
    }

    const ruleData = {
        item_id: itemId,
        card_id: parseInt(cardId),
        delivery_count: parseInt(deliveryCount),
        enabled: enabled,
        description: description,
        generate_image: generateImage,
        is_multi_spec: isMultiSpec,
        spec_name: isMultiSpec ? specName : null,
        spec_value: isMultiSpec ? specValue : null
    };

    const response = await fetch(`${apiBase}/delivery-rules/${ruleId}`, {
        method: 'PUT',
        headers: {
        'Authorization': `Bearer ${authToken}`,
        'Content-Type': 'application/json'
        },
        body: JSON.stringify(ruleData)
    });

    if (response.ok) {
        showToast('发货规则更新成功', 'success');
        bootstrap.Modal.getInstance(document.getElementById('editDeliveryRuleModal')).hide();
        loadDeliveryRules();
    } else {
        const error = await response.text();
        showToast(`更新失败: ${error}`, 'danger');
    }
    } catch (error) {
    console.error('更新发货规则失败:', error);
    showToast('更新发货规则失败', 'danger');
    }
}

// 测试发货规则（占位函数）
function testDeliveryRule(ruleId) {
    showToast('测试功能开发中...', 'info');
}

// 全局变量存储当前规则数据，用于详情显示
let currentDeliveryRules = [];

// 显示分组规则详情
function showGroupedRulesDetail(ruleIds) {
    try {
        // 如果传入的是字符串，需要解析；如果是数组，直接使用
        const ids = typeof ruleIds === 'string' ? JSON.parse(ruleIds.replace(/&quot;/g, '"')) : ruleIds;
        
        // 去重规则ID
        const uniqueIds = [...new Set(ids)];
        
        let detailHtml = '<div class="list-group">';
        
        // 从当前规则数据中找到对应的详情
        uniqueIds.forEach((id, index) => {
            const rule = currentDeliveryRules.find(r => r.id === id);
            const itemId = rule ? rule.item_id : '未知';
            const cardName = rule ? rule.card_name : '未知卡券';
            
            detailHtml += `
                <div class="list-group-item d-flex justify-content-between align-items-center">
                    <div>
                        <span class="fw-bold">规则 #${id}</span>
                        <br>
                        <small class="text-muted">商品ID: ${itemId} → ${cardName}</small>
                    </div>
                    <div class="btn-group" role="group">
                        <button class="btn btn-sm btn-outline-primary" onclick="editDeliveryRule(${id})" title="编辑">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteDeliveryRule(${id})" title="删除">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                </div>
            `;
        });
        detailHtml += '</div>';
        
        // 创建一个简单的模态框显示详情
        const modalHtml = `
            <div class="modal fade" id="groupedRulesDetailModal" tabindex="-1">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">
                                <i class="bi bi-layers me-2"></i>
                                分组规则详情
                            </h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            ${detailHtml}
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 移除已存在的模态框
        const existingModal = document.getElementById('groupedRulesDetailModal');
        if (existingModal) {
            existingModal.remove();
        }
        
        // 添加新模态框
        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('groupedRulesDetailModal'));
        modal.show();
        
    } catch (error) {
        console.error('显示分组规则详情失败:', error);
        showToast('显示详情失败', 'danger');
    }
}

// 删除分组规则
async function deleteGroupedRules(ruleIds) {
    try {
        // 如果传入的是字符串，需要解析；如果是数组，直接使用
        const ids = typeof ruleIds === 'string' ? JSON.parse(ruleIds.replace(/&quot;/g, '"')) : ruleIds;
        
        if (!confirm(`确定要删除这 ${ids.length} 条发货规则吗？此操作不可撤销。`)) {
            return;
        }
        
        // 逐个删除规则
        let successCount = 0;
        for (const id of ids) {
            try {
                const response = await fetch(`${apiBase}/delivery-rules/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                if (response.ok) {
                    successCount++;
                }
            } catch (error) {
                console.error(`删除规则 ${id} 失败:`, error);
            }
        }
        
        if (successCount > 0) {
            showToast(`成功删除 ${successCount} 条发货规则`, 'success');
            loadDeliveryRules();
        } else {
            showToast('删除失败', 'danger');
        }
        
    } catch (error) {
        console.error('删除分组规则失败:', error);
        showToast('删除失败', 'danger');
    }
}

// 删除发货规则
async function deleteDeliveryRule(ruleId) {
    if (confirm('确定要删除这个发货规则吗？删除后无法恢复！')) {
    try {
        const response = await fetch(`${apiBase}/delivery-rules/${ruleId}`, {
        method: 'DELETE',
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
        });

        if (response.ok) {
        showToast('发货规则删除成功', 'success');
        loadDeliveryRules();
        } else {
        const error = await response.text();
        showToast(`删除失败: ${error}`, 'danger');
        }
    } catch (error) {
        console.error('删除发货规则失败:', error);
        showToast('删除发货规则失败', 'danger');
    }
    }
}



// ==================== 系统设置功能 ====================



document.addEventListener('DOMContentLoaded', function() {
    // 关键词未匹配回复表单提交处理（移到loadSystemSettings函数中）

    // 原密码表单处理已移至个人信息页面

    // 个人信息表单提交处理
    const userInfoForm = document.getElementById('userInfoForm');
    if (userInfoForm) {
        userInfoForm.addEventListener('submit', updateUserInfo);
    }

    // 个人密码表单提交处理
    const personalPasswordForm = document.getElementById('personalPasswordForm');
    if (personalPasswordForm) {
        personalPasswordForm.addEventListener('submit', updatePersonalPassword);
    }
});

// ==================== 个人信息管理功能 ====================

// 加载个人信息
async function loadPersonalInfo() {
    try {
        toggleLoading(true);
        
        // 获取当前用户信息
        const userResponse = await fetch(`${apiBase}/current-user`, {
            headers: { 'Authorization': `Bearer ${authToken}` }
        });
        
        if (userResponse.ok) {
            const userInfo = await userResponse.json();
            
            // 填充基本信息表单
            document.getElementById('userUsername').value = userInfo.username || '';
            document.getElementById('userEmail').value = userInfo.email || '';
            document.getElementById('userPhone').value = userInfo.phone || '';
            document.getElementById('userNickname').value = userInfo.nickname || '';
            
            // 更新聚合豆余额显示
            const balance = userInfo.balance || 0;
            document.getElementById('userBalance').textContent = balance.toFixed(2);
            
            // 更新注册时间显示
            if (userInfo.created_at) {
                const joinDate = new Date(userInfo.created_at);
                document.getElementById('userJoinDate').textContent = joinDate.toLocaleDateString();
            }
            
            // 检查是否为管理员，显示/隐藏管理员功能
            await checkAndShowAdminBalanceManagement();
        }
        
        // 获取用户统计信息
        await loadUserStats();
        
    } catch (error) {
        console.error('加载个人信息失败:', error);
        showToast('加载个人信息失败', 'danger');
    } finally {
        toggleLoading(false);
    }
}

// 加载用户统计信息
async function loadUserStats() {
    try {
        // 获取用户的账号数量
        const accountsResponse = await fetch(`${apiBase}/cookies`, {
            headers: { 'Authorization': `Bearer ${authToken}` }
        });
        
        let accountCount = 0;
        
        if (accountsResponse.ok) {
            const accounts = await accountsResponse.json();
            accountCount = accounts.length;
        }
        
        // 获取订单数量
        const ordersResponse = await fetch(`${apiBase}/orders?page=1&page_size=1`, {
            headers: { 'Authorization': `Bearer ${authToken}` }
        });
        
        let orderCount = 0;
        if (ordersResponse.ok) {
            const ordersData = await ordersResponse.json();
            orderCount = ordersData.total || 0;
        }
        
        // 更新统计显示
        document.getElementById('userAccountCount').textContent = accountCount;
        document.getElementById('userOrderCount').textContent = orderCount;
        
    } catch (error) {
        console.error('加载用户统计失败:', error);
    }
}

// 更新用户信息
async function updateUserInfo(event) {
    event.preventDefault();
    
    try {
        toggleLoading(true);
        
        const formData = {
            email: document.getElementById('userEmail').value.trim(),
            phone: document.getElementById('userPhone').value.trim(),
            nickname: document.getElementById('userNickname').value.trim()
        };
        
        // 验证邮箱格式
        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailPattern.test(formData.email)) {
            showToast('请输入有效的邮箱地址', 'warning');
            return;
        }
        
        const response = await fetch(`${apiBase}/user-info`, {
            method: 'PUT',
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        });
        
        if (response.ok) {
            showToast('个人信息更新成功', 'success');
        } else {
            const error = await response.text();
            showToast(`更新失败: ${error}`, 'danger');
        }
        
    } catch (error) {
        console.error('更新用户信息失败:', error);
        showToast('更新用户信息失败', 'danger');
    } finally {
        toggleLoading(false);
    }
}

// 更新个人密码
async function updatePersonalPassword(event) {
    event.preventDefault();
    
    const currentPassword = document.getElementById('personalCurrentPassword').value;
    const newPassword = document.getElementById('personalNewPassword').value;
    const confirmPassword = document.getElementById('personalConfirmPassword').value;
    
    if (newPassword !== confirmPassword) {
        showToast('新密码和确认密码不匹配', 'warning');
        return;
    }
    
    if (newPassword.length < 6) {
        showToast('新密码长度至少6位', 'warning');
        return;
    }
    
    try {
        toggleLoading(true);
        
        const response = await fetch(`${apiBase}/change-password`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                current_password: currentPassword,
                new_password: newPassword
            })
        });
        
        if (response.ok) {
            const result = await response.json();
            if (result.success) {
                showToast('密码更新成功，请重新登录', 'success');
                document.getElementById('personalPasswordForm').reset();
                // 3秒后跳转到登录页面
                setTimeout(() => {
                    localStorage.removeItem('auth_token');
                    window.location.href = '/login.html';
                }, 3000);
            } else {
                showToast(`密码更新失败: ${result.message}`, 'danger');
            }
        } else {
            const error = await response.text();
            showToast(`密码更新失败: ${error}`, 'danger');
        }
        
    } catch (error) {
        console.error('密码更新失败:', error);
        showToast('密码更新失败', 'danger');
    } finally {
        toggleLoading(false);
    }
}

// ==================== 聚合豆管理功能 ====================

// 全局变量
let currentBalanceRecordsPage = 1;
let totalBalanceRecordsPages = 0;

// 检查并显示管理员余额管理功能
async function checkAndShowAdminBalanceManagement() {
    try {
        const response = await fetch(`${apiBase}/verify`, {
            headers: { 'Authorization': `Bearer ${authToken}` }
        });
        
        if (response.ok) {
            const result = await response.json();
            const isAdmin = result.is_admin === true;
            
            // 显示/隐藏管理员余额管理功能
            const adminBalanceManagement = document.getElementById('adminBalanceManagement');
            if (adminBalanceManagement) {
                adminBalanceManagement.style.display = isAdmin ? 'block' : 'none';
            }
            
            // 如果是管理员，绑定表单事件
            if (isAdmin) {
                const balanceAdjustForm = document.getElementById('balanceAdjustForm');
                if (balanceAdjustForm) {
                    balanceAdjustForm.removeEventListener('submit', handleBalanceAdjust);
                    balanceAdjustForm.addEventListener('submit', handleBalanceAdjust);
                }
            }
        }
    } catch (error) {
        console.error('检查管理员权限失败:', error);
    }
}

// 管理员调整余额
async function handleBalanceAdjust(event) {
    event.preventDefault();
    
    const amount = parseFloat(document.getElementById('balanceAmount').value);
    const description = document.getElementById('balanceDescription').value.trim();
    
    if (isNaN(amount) || amount === 0) {
        showToast('请输入有效的调整金额', 'warning');
        return;
    }
    
    // 显示确认对话框
    const actionText = amount > 0 ? '充值' : '扣除';
    const amountText = Math.abs(amount).toFixed(2);
    const confirmMessage = `确认要${actionText} ${amountText} 聚合豆吗？${description ? '\n操作说明：' + description : ''}`;
    
    if (!confirm(confirmMessage)) {
        return;
    }
    
    try {
        toggleLoading(true);
        
        // 获取当前用户信息
        const userResponse = await fetch(`${apiBase}/current-user`, {
            headers: { 'Authorization': `Bearer ${authToken}` }
        });
        
        if (!userResponse.ok) {
            showToast('获取用户信息失败', 'danger');
            return;
        }
        
        const userInfo = await userResponse.json();
        const userId = userInfo.id;
        
        const response = await fetch(`${apiBase}/admin/adjust-balance`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                user_id: userId,
                operation: amount > 0 ? 'add' : 'subtract',
                amount: Math.abs(amount),
                reason: description
            })
        });
        
        if (response.ok) {
            const result = await response.json();
            if (result.success) {
                const actionText = amount > 0 ? '充值' : '扣除';
                const amountText = Math.abs(amount).toFixed(2);
                
                // 显示详细的成功消息
                showToast(`
                    <i class="bi bi-check-circle-fill me-2"></i>
                    <strong>${actionText}成功！</strong><br/>
                    金额：${amountText} 聚合豆<br/>
                    当前余额：${result.new_balance.toFixed(2)} 聚合豆
                `, 'success');
                
                // 更新余额显示（带动画效果）
                const balanceElement = document.getElementById('userBalance');
                balanceElement.style.transition = 'all 0.3s ease';
                balanceElement.style.transform = 'scale(1.1)';
                balanceElement.style.color = '#198754';
                balanceElement.textContent = result.new_balance.toFixed(2);
                
                // 恢复原始样式
                setTimeout(() => {
                    balanceElement.style.transform = 'scale(1)';
                    balanceElement.style.color = '';
                }, 300);
                
                // 重置表单
                document.getElementById('balanceAdjustForm').reset();
                
                // 如果消费记录模态框是打开的，刷新记录
                const modal = document.getElementById('balanceRecordsModal');
                if (modal && modal.classList.contains('show')) {
                    await refreshBalanceRecords();
                }
            } else {
                showToast(`
                    <i class="bi bi-exclamation-triangle-fill me-2"></i>
                    <strong>操作失败！</strong><br/>
                    ${result.message}
                `, 'danger');
            }
        } else {
            const error = await response.text();
            showToast(`
                <i class="bi bi-x-circle-fill me-2"></i>
                <strong>调整余额失败！</strong><br/>
                ${error}
            `, 'danger');
        }
        
    } catch (error) {
        console.error('调整余额失败:', error);
        showToast('调整余额失败', 'danger');
    } finally {
        toggleLoading(false);
    }
}

// 显示聚合豆消费记录模态框
async function loadBalanceRecords(page = 1) {
    try {
        toggleLoading(true);
        
        const success = await fetchBalanceRecordsData(page);
        
        if (success) {
            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('balanceRecordsModal'));
            
            // 添加模态框关闭事件监听器，确保loading状态被清除
            modal._element.addEventListener('hidden.bs.modal', function () {
                toggleLoading(false);
            }, { once: true });
            
            modal.show();
        }
        
    } catch (error) {
        console.error('加载消费记录失败:', error);
        showToast('加载消费记录失败', 'danger');
    } finally {
        toggleLoading(false);
    }
}

// 刷新聚合豆消费记录数据（用于模态框内的刷新按钮）
async function refreshBalanceRecords(page = 1) {
    try {
        toggleLoading(true);
        await fetchBalanceRecordsData(page);
    } catch (error) {
        console.error('刷新消费记录失败:', error);
        showToast('刷新消费记录失败', 'danger');
    } finally {
        toggleLoading(false);
    }
}

// 获取聚合豆消费记录数据（共用逻辑）
async function fetchBalanceRecordsData(page = 1) {
    const pageSize = document.getElementById('balanceRecordsPageSize')?.value || 20;
    
    const response = await fetch(`${apiBase}/balance-records?page=${page}&page_size=${pageSize}`, {
        headers: { 'Authorization': `Bearer ${authToken}` }
    });
    
    if (response.ok) {
        const result = await response.json();
        
        if (result.success) {
            const data = result.data;
            const records = data.records || [];
            const pagination = data.pagination || {};
            
            // 更新全局分页变量
            currentBalanceRecordsPage = pagination.current_page || 1;
            totalBalanceRecordsPages = pagination.total_pages || 0;
            
            // 渲染记录列表
            renderBalanceRecords(records);
            
            // 更新分页信息
            updateBalanceRecordsPagination(pagination);
            
            return true;
        } else {
            showToast('获取消费记录失败', 'danger');
            return false;
        }
    } else {
        showToast('获取消费记录失败', 'danger');
        return false;
    }
}

// 渲染聚合豆消费记录
function renderBalanceRecords(records) {
    const tbody = document.getElementById('balanceRecordsTableBody');
    
    if (!records || records.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="6" class="text-center text-muted py-4">
                    <i class="bi bi-coin fs-1 d-block mb-2"></i>
                    <p>暂无消费记录</p>
                </td>
            </tr>
        `;
        return;
    }
    
    tbody.innerHTML = records.map(record => {
        const amount = parseFloat(record.amount);
        const amountClass = amount >= 0 ? 'text-success' : 'text-danger';
        const amountIcon = amount >= 0 ? 'bi-plus-circle' : 'bi-dash-circle';
        const amountText = amount >= 0 ? `+${amount.toFixed(2)}` : amount.toFixed(2);
        
        // 记录类型显示
        const typeMap = {
            'consume': { text: '订单消费', class: 'bg-danger' },
            'recharge': { text: '充值', class: 'bg-success' },
            'admin_adjust': { text: '管理员调整', class: 'bg-warning' }
        };
        const typeInfo = typeMap[record.record_type] || { text: record.record_type, class: 'bg-secondary' };
        
        return `
            <tr>
                <td>
                    ${record.order_id ? `
                        <span class="text-primary">${record.order_id}</span>
                    ` : '<span class="text-muted">-</span>'}
                </td>
                <td>
                    <span class="${amountClass}">
                        <i class="bi ${amountIcon} me-1"></i>
                        ${amountText}
                    </span>
                </td>
                <td>
                    <span class="fw-bold">${record.balance_after.toFixed(2)}</span>
                </td>
                <td>
                    <span class="badge ${typeInfo.class}">${typeInfo.text}</span>
                </td>
                <td>
                    <span class="text-muted small">${record.description || '-'}</span>
                    ${record.admin_username ? `<br><small class="text-info">操作者: ${record.admin_username}</small>` : ''}
                </td>
                <td>
                    <small class="text-muted">${formatDateTime(record.created_at)}</small>
                </td>
            </tr>
        `;
    }).join('');
}

// 更新聚合豆记录分页信息
function updateBalanceRecordsPagination(pagination) {
    const { current_page, page_size, total_count, total_pages, has_prev, has_next } = pagination;
    
    // 更新记录计数
    document.getElementById('balanceRecordCount').textContent = `${total_count} 条记录`;
    
    // 更新分页信息显示
    const startRecord = total_count === 0 ? 0 : (current_page - 1) * page_size + 1;
    const endRecord = Math.min(current_page * page_size, total_count);
    document.getElementById('balanceRecordsPageInfo').textContent = 
        `显示第 ${startRecord}-${endRecord} 条，共 ${total_count} 条记录`;
    
    // 更新分页按钮状态
    document.getElementById('balanceRecordsFirstPage').disabled = !has_prev;
    document.getElementById('balanceRecordsPrevPage').disabled = !has_prev;
    document.getElementById('balanceRecordsNextPage').disabled = !has_next;
    document.getElementById('balanceRecordsLastPage').disabled = !has_next;
    
    // 更新页码显示
    document.getElementById('balanceRecordsPageInput').value = current_page;
    document.getElementById('balanceRecordsTotalPages').textContent = total_pages;
}

// 跳转到指定页码
function goToBalanceRecordsPage(page) {
    if (page < 1 || page > totalBalanceRecordsPages) {
        return;
    }
    refreshBalanceRecords(page);
}

// 刷新聚合豆余额显示
async function refreshUserBalance() {
    try {
        const response = await fetch(`${apiBase}/user-balance`, {
            headers: { 'Authorization': `Bearer ${authToken}` }
        });
        
        if (response.ok) {
            const result = await response.json();
            if (result.success) {
                document.getElementById('userBalance').textContent = result.balance.toFixed(2);
            }
        }
    } catch (error) {
        console.error('刷新余额失败:', error);
    }
}

// ==================== 备份管理功能 ====================

// 下载数据库备份
async function downloadDatabaseBackup() {
    try {
    showToast('正在准备数据库备份，请稍候...', 'info');

    const response = await fetch(`${apiBase}/admin/backup/download`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        // 获取文件名
        const contentDisposition = response.headers.get('content-disposition');
        let filename = 'xianyu_backup.db';
        if (contentDisposition) {
        const filenameMatch = contentDisposition.match(/filename="(.+)"/);
        if (filenameMatch) {
            filename = filenameMatch[1];
        }
        }

        // 下载文件
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);

        showToast('数据库备份下载成功', 'success');
    } else {
        const error = await response.text();
        showToast(`下载失败: ${error}`, 'danger');
    }
    } catch (error) {
    console.error('下载数据库备份失败:', error);
    showToast('下载数据库备份失败', 'danger');
    }
}

// 上传数据库备份
async function uploadDatabaseBackup() {
    const fileInput = document.getElementById('databaseFile');
    const file = fileInput.files[0];

    if (!file) {
    showToast('请选择数据库文件', 'warning');
    return;
    }

    if (!file.name.endsWith('.db')) {
    showToast('只支持.db格式的数据库文件', 'warning');
    return;
    }

    // 文件大小检查（限制100MB）
    if (file.size > 100 * 1024 * 1024) {
    showToast('数据库文件大小不能超过100MB', 'warning');
    return;
    }

    if (!confirm('恢复数据库将完全替换当前所有数据，包括所有用户、Cookie、卡券等信息。\n\n此操作不可撤销！\n\n确定要继续吗？')) {
    return;
    }

    try {
    showToast('正在上传并恢复数据库，请稍候...', 'info');

    const formData = new FormData();
    formData.append('backup_file', file);

    const response = await fetch(`${apiBase}/admin/backup/upload`, {
        method: 'POST',
        headers: {
        'Authorization': `Bearer ${authToken}`
        },
        body: formData
    });

    if (response.ok) {
        const result = await response.json();
        showToast(`数据库恢复成功！包含 ${result.user_count} 个用户`, 'success');

        // 清空文件选择
        fileInput.value = '';

        // 提示用户刷新页面
        setTimeout(() => {
        if (confirm('数据库已恢复，建议刷新页面以加载新数据。是否立即刷新？')) {
            window.location.reload();
        }
        }, 2000);

    } else {
        const error = await response.json();
        showToast(`恢复失败: ${error.detail}`, 'danger');
    }
    } catch (error) {
    console.error('上传数据库备份失败:', error);
    showToast('上传数据库备份失败', 'danger');
    }
}

// 导出备份（JSON格式，兼容旧版本）
async function exportBackup() {
    try {
    showToast('正在导出备份，请稍候...', 'info');

    const response = await fetch(`${apiBase}/backup/export`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        const backupData = await response.json();

        // 生成文件名
        const now = new Date();
        const timestamp = now.getFullYear() +
                        String(now.getMonth() + 1).padStart(2, '0') +
                        String(now.getDate()).padStart(2, '0') + '_' +
                        String(now.getHours()).padStart(2, '0') +
                        String(now.getMinutes()).padStart(2, '0') +
                        String(now.getSeconds()).padStart(2, '0');
        const filename = `xianyu_backup_${timestamp}.json`;

        // 创建下载链接
        const blob = new Blob([JSON.stringify(backupData, null, 2)], { type: 'application/json' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);

        showToast('备份导出成功', 'success');
    } else {
        const error = await response.text();
        showToast(`导出失败: ${error}`, 'danger');
    }
    } catch (error) {
    console.error('导出备份失败:', error);
    showToast('导出备份失败', 'danger');
    }
}

// 导入备份
async function importBackup() {
    const fileInput = document.getElementById('backupFile');
    const file = fileInput.files[0];

    if (!file) {
    showToast('请选择备份文件', 'warning');
    return;
    }

    if (!file.name.endsWith('.json')) {
    showToast('只支持JSON格式的备份文件', 'warning');
    return;
    }

    if (!confirm('导入备份将覆盖当前所有数据，确定要继续吗？')) {
    return;
    }

    try {
    showToast('正在导入备份，请稍候...', 'info');

    const formData = new FormData();
    formData.append('file', file);

    const response = await fetch(`${apiBase}/backup/import`, {
        method: 'POST',
        headers: {
        'Authorization': `Bearer ${authToken}`
        },
        body: formData
    });

    if (response.ok) {
        showToast('备份导入成功！正在刷新数据...', 'success');

        // 清空文件选择
        fileInput.value = '';

        // 清除前端缓存
        clearKeywordCache();

        // 延迟一下再刷新数据，确保后端缓存已更新
        setTimeout(async () => {
        try {
            // 如果当前在关键字管理页面，重新加载数据
            if (currentCookieId) {
            await loadAccountKeywords();
            }

            // 刷新仪表盘数据
            if (document.getElementById('dashboard-section').classList.contains('active')) {
            await loadDashboard();
            }

            // 刷新账号列表
            if (document.getElementById('accounts-section').classList.contains('active')) {
            await loadCookies();
            }

            showToast('数据刷新完成！', 'success');
        } catch (error) {
            console.error('刷新数据失败:', error);
            showToast('备份导入成功，但数据刷新失败，请手动刷新页面', 'warning');
        }
        }, 1000);
    } else {
        const error = await response.text();
        showToast(`导入失败: ${error}`, 'danger');
    }
    } catch (error) {
    console.error('导入备份失败:', error);
    showToast('导入备份失败', 'danger');
    }
}

// 刷新系统缓存
async function reloadSystemCache() {
    try {
    showToast('正在刷新系统缓存...', 'info');

    const response = await fetch(`${apiBase}/system/reload-cache`, {
        method: 'POST',
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        const result = await response.json();
        showToast('系统缓存刷新成功！关键字等数据已更新', 'success');

        // 清除前端缓存
        clearKeywordCache();

        // 如果当前在关键字管理页面，重新加载数据
        if (currentCookieId) {
        setTimeout(() => {
            loadAccountKeywords();
        }, 500);
        }
    } else {
        const error = await response.text();
        showToast(`刷新缓存失败: ${error}`, 'danger');
    }
    } catch (error) {
    console.error('刷新系统缓存失败:', error);
    showToast('刷新系统缓存失败', 'danger');
    }
}

// ================================
// 【商品管理菜单】相关功能
// ================================

// 切换商品多规格状态
async function toggleItemMultiSpec(cookieId, itemId, isMultiSpec) {
    try {
    const response = await fetch(`${apiBase}/items/${encodeURIComponent(cookieId)}/${encodeURIComponent(itemId)}/multi-spec`, {
        method: 'PUT',
        headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify({
        is_multi_spec: isMultiSpec
        })
    });

    if (response.ok) {
        showToast(`${isMultiSpec ? '开启' : '关闭'}多规格成功`, 'success');
        // 刷新商品列表
        await refreshItemsData();
    } else {
        const errorData = await response.json();
        throw new Error(errorData.error || '操作失败');
    }
    } catch (error) {
    console.error('切换多规格状态失败:', error);
    showToast(`切换多规格状态失败: ${error.message}`, 'danger');
    }
}

// 加载商品列表
async function loadItems() {
    try {
    // 先加载Cookie列表用于筛选
    await loadCookieFilter();

    // 加载商品列表
    await refreshItemsData();
    } catch (error) {
    console.error('加载商品列表失败:', error);
    showToast('加载商品列表失败', 'danger');
    }
}

// 只刷新商品数据，不重新加载筛选器
async function refreshItemsData() {
    try {
    const selectedCookie = document.getElementById('itemCookieFilter').value;
    if (selectedCookie) {
        await loadItemsByCookie();
    } else {
        await loadAllItems();
    }
    } catch (error) {
    console.error('刷新商品数据失败:', error);
    showToast('刷新商品数据失败', 'danger');
    }
}

// 加载Cookie筛选选项
async function loadCookieFilter() {
    try {
    const response = await fetch(`${apiBase}/cookies/details`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        const accounts = await response.json();
        const select = document.getElementById('itemCookieFilter');

        // 保存当前选择的值
        const currentValue = select.value;

        // 清空现有选项（保留"所有账号"）
        select.innerHTML = '<option value="">所有账号</option>';

        if (accounts.length === 0) {
        const option = document.createElement('option');
        option.value = '';
        option.textContent = '❌ 暂无账号';
        option.disabled = true;
        select.appendChild(option);
        return;
    }

        // 分组显示：先显示启用的账号，再显示禁用的账号
        const enabledAccounts = accounts.filter(account => {
        const enabled = account.enabled === undefined ? true : account.enabled;
        return enabled;
        });
        const disabledAccounts = accounts.filter(account => {
        const enabled = account.enabled === undefined ? true : account.enabled;
        return !enabled;
        });

        // 添加启用的账号
        enabledAccounts.forEach(account => {
        const option = document.createElement('option');
        option.value = account.id;
        const remarkText = account.remark ? ` (${account.remark})` : '';
        option.textContent = `🟢 ${account.id}${remarkText}`;
        select.appendChild(option);
        });

        // 添加禁用的账号
        if (disabledAccounts.length > 0) {
        // 添加分隔线
        if (enabledAccounts.length > 0) {
            const separator = document.createElement('option');
            separator.value = '';
            separator.textContent = '────────────────';
            separator.disabled = true;
            select.appendChild(separator);
        }

        disabledAccounts.forEach(account => {
            const option = document.createElement('option');
            option.value = account.id;
            const remarkText = account.remark ? ` (${account.remark})` : '';
            option.textContent = `🔴 ${account.id}${remarkText} (已禁用)`;
            select.appendChild(option);
        });
        }

        // 恢复之前选择的值
        if (currentValue) {
        select.value = currentValue;
        }
    }
    } catch (error) {
    console.error('加载Cookie列表失败:', error);
    showToast('加载账号列表失败', 'danger');
    }
}

// 加载所有商品
async function loadAllItems() {
    try {
    const response = await fetch(`${apiBase}/items`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        const data = await response.json();
        displayItems(data.items);
    } else {
        throw new Error('获取商品列表失败');
    }
    } catch (error) {
    console.error('加载商品列表失败:', error);
    showToast('加载商品列表失败', 'danger');
    }
}

// 按Cookie加载商品
async function loadItemsByCookie() {
    const cookieId = document.getElementById('itemCookieFilter').value;

    if (!cookieId) {
    await loadAllItems();
    return;
    }

    try {
    const response = await fetch(`${apiBase}/items/cookie/${encodeURIComponent(cookieId)}`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });

        if (response.ok) {
        const data = await response.json();
        displayItems(data.items);
    } else {
        throw new Error('获取商品列表失败');
    }
    } catch (error) {
    console.error('加载商品列表失败:', error);
    showToast('加载商品列表失败', 'danger');
    }
}

// 显示商品列表
function displayItems(items) {
    // 存储所有商品数据
    allItemsData = items || [];

    // 应用搜索过滤
    applyItemsFilter();

    // 显示当前页数据
    displayCurrentPageItems();

    // 更新分页控件
    updateItemsPagination();
}

// 应用搜索过滤
function applyItemsFilter() {
    const searchKeyword = currentSearchKeyword.toLowerCase().trim();

    if (!searchKeyword) {
        filteredItemsData = [...allItemsData];
    } else {
        filteredItemsData = allItemsData.filter(item => {
            const title = (item.item_title || '').toLowerCase();
            const detail = getItemDetailText(item.item_detail || '').toLowerCase();
            return title.includes(searchKeyword) || detail.includes(searchKeyword);
        });
    }

    // 重置到第一页
    currentItemsPage = 1;

    // 计算总页数
    totalItemsPages = Math.ceil(filteredItemsData.length / itemsPerPage);

    // 更新搜索统计
    updateItemsSearchStats();
}

// 获取商品详情的纯文本内容
function getItemDetailText(itemDetail) {
    if (!itemDetail) return '';

    try {
        // 尝试解析JSON
        const detail = JSON.parse(itemDetail);
        if (detail.content) {
            return detail.content;
        }
        return itemDetail;
    } catch (e) {
        // 如果不是JSON格式，直接返回原文本
        return itemDetail;
    }
}

// 显示当前页的商品数据
function displayCurrentPageItems() {
    const tbody = document.getElementById('itemsTableBody');

    if (!filteredItemsData || filteredItemsData.length === 0) {
        tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">暂无商品数据</td></tr>';
        resetItemsSelection();
        return;
    }

    // 计算当前页的数据范围
    const startIndex = (currentItemsPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    const currentPageItems = filteredItemsData.slice(startIndex, endIndex);

    const itemsHtml = currentPageItems.map(item => {
        // 处理商品标题显示
        let itemTitleDisplay = item.item_title || '未设置';
        if (itemTitleDisplay.length > 30) {
            itemTitleDisplay = itemTitleDisplay.substring(0, 30) + '...';
        }

        // 处理商品详情显示
        let itemDetailDisplay = '未设置';
        if (item.item_detail) {
            const detailText = getItemDetailText(item.item_detail);
            itemDetailDisplay = detailText.substring(0, 50) + (detailText.length > 50 ? '...' : '');
        }

        // 多规格状态显示
        const isMultiSpec = item.is_multi_spec;
        const multiSpecDisplay = isMultiSpec ?
            '<span class="badge bg-success">多规格</span>' :
            '<span class="badge bg-secondary">普通</span>';

        return `
            <tr>
            <td>
                <input type="checkbox" name="itemCheckbox"
                        data-cookie-id="${escapeHtml(item.cookie_id)}"
                        data-item-id="${escapeHtml(item.item_id)}"
                        onchange="updateSelectAllState()">
            </td>
            <td>${escapeHtml(item.cookie_id)}</td>
            <td>${escapeHtml(item.item_id)}</td>
            <td title="${escapeHtml(item.item_title || '未设置')}">${escapeHtml(itemTitleDisplay)}</td>
            <td title="${escapeHtml(getItemDetailText(item.item_detail || ''))}">${escapeHtml(itemDetailDisplay)}</td>
            <td>${multiSpecDisplay}</td>
            <td>${formatDateTime(item.updated_at)}</td>
            <td>
                <div class="btn-group" role="group">
                <button class="btn btn-sm btn-outline-primary" onclick="editItem('${escapeHtml(item.cookie_id)}', '${escapeHtml(item.item_id)}')" title="编辑详情">
                    <i class="bi bi-pencil"></i>
                </button>
                <button class="btn btn-sm btn-outline-danger" onclick="deleteItem('${escapeHtml(item.cookie_id)}', '${escapeHtml(item.item_id)}', '${escapeHtml(item.item_title || item.item_id)}')" title="删除">
                    <i class="bi bi-trash"></i>
                </button>
                <button class="btn btn-sm btn-outline-info" onclick="showAutoReplyModal('${escapeHtml(item.cookie_id)}', '${escapeHtml(item.item_id)}')" title="设置自动回复">
                    <i class="bi bi-chat-dots"></i>
                </button>
                <button class="btn btn-sm btn-outline-success" onclick="showAutoShippingModal('${escapeHtml(item.cookie_id)}', '${escapeHtml(item.item_id)}')" title="设置自动发货">
                    <i class="bi bi-truck"></i>
                </button>
                </div>
            </td>
            </tr>
        `;
    }).join('');

    // 更新表格内容
    tbody.innerHTML = itemsHtml;

    // 重置选择状态
    resetItemsSelection();
}

// 重置商品选择状态
function resetItemsSelection() {
    const selectAllCheckbox = document.getElementById('selectAllItems');
    if (selectAllCheckbox) {
        selectAllCheckbox.checked = false;
        selectAllCheckbox.indeterminate = false;
    }
    updateBatchDeleteButton();
}

// 商品搜索过滤函数
function filterItems() {
    const searchInput = document.getElementById('itemSearchInput');
    currentSearchKeyword = searchInput ? searchInput.value : '';

    // 应用过滤
    applyItemsFilter();

    // 显示当前页数据
    displayCurrentPageItems();

    // 更新分页控件
    updateItemsPagination();
}

// 更新搜索统计信息
function updateItemsSearchStats() {
    const statsElement = document.getElementById('itemSearchStats');
    const statsTextElement = document.getElementById('itemSearchStatsText');

    if (!statsElement || !statsTextElement) return;

    if (currentSearchKeyword) {
        statsTextElement.textContent = `搜索"${currentSearchKeyword}"，找到 ${filteredItemsData.length} 个商品`;
        statsElement.style.display = 'block';
    } else {
        statsElement.style.display = 'none';
    }
}

// 更新分页控件
function updateItemsPagination() {
    const paginationElement = document.getElementById('itemsPagination');
    const pageInfoElement = document.getElementById('itemsPageInfo');
    const totalPagesElement = document.getElementById('itemsTotalPages');
    const pageInputElement = document.getElementById('itemsPageInput');

    if (!paginationElement) return;

    // 分页控件总是显示
    paginationElement.style.display = 'block';

    // 更新页面信息
    const startIndex = (currentItemsPage - 1) * itemsPerPage + 1;
    const endIndex = Math.min(currentItemsPage * itemsPerPage, filteredItemsData.length);

    if (pageInfoElement) {
        pageInfoElement.textContent = `显示第 ${startIndex}-${endIndex} 条，共 ${filteredItemsData.length} 条记录`;
    }

    if (totalPagesElement) {
        totalPagesElement.textContent = totalItemsPages;
    }

    if (pageInputElement) {
        pageInputElement.value = currentItemsPage;
        pageInputElement.max = totalItemsPages;
    }

    // 更新分页按钮状态
    updateItemsPaginationButtons();
}

// 更新分页按钮状态
function updateItemsPaginationButtons() {
    const firstPageBtn = document.getElementById('itemsFirstPage');
    const prevPageBtn = document.getElementById('itemsPrevPage');
    const nextPageBtn = document.getElementById('itemsNextPage');
    const lastPageBtn = document.getElementById('itemsLastPage');

    if (firstPageBtn) firstPageBtn.disabled = currentItemsPage <= 1;
    if (prevPageBtn) prevPageBtn.disabled = currentItemsPage <= 1;
    if (nextPageBtn) nextPageBtn.disabled = currentItemsPage >= totalItemsPages;
    if (lastPageBtn) lastPageBtn.disabled = currentItemsPage >= totalItemsPages;
}

// 跳转到指定页面
function goToItemsPage(page) {
    if (page < 1 || page > totalItemsPages) return;

    currentItemsPage = page;
    displayCurrentPageItems();
    updateItemsPagination();
}

// 处理页面输入框的回车事件
function handleItemsPageInput(event) {
    if (event.key === 'Enter') {
        const pageInput = event.target;
        const page = parseInt(pageInput.value);

        if (page >= 1 && page <= totalItemsPages) {
            goToItemsPage(page);
        } else {
            pageInput.value = currentItemsPage;
        }
    }
}

// 改变每页显示数量
function changeItemsPageSize() {
    const pageSizeSelect = document.getElementById('itemsPageSize');
    if (!pageSizeSelect) return;

    itemsPerPage = parseInt(pageSizeSelect.value);

    // 重新计算总页数
    totalItemsPages = Math.ceil(filteredItemsData.length / itemsPerPage);

    // 调整当前页码，确保不超出范围
    if (currentItemsPage > totalItemsPages) {
        currentItemsPage = Math.max(1, totalItemsPages);
    }

    // 重新显示数据
    displayCurrentPageItems();
    updateItemsPagination();
}

// 初始化商品列表搜索功能
function initItemsSearch() {
    // 初始化分页大小
    const pageSizeSelect = document.getElementById('itemsPageSize');
    if (pageSizeSelect) {
        itemsPerPage = parseInt(pageSizeSelect.value) || 20;
        pageSizeSelect.addEventListener('change', changeItemsPageSize);
    }

    // 初始化搜索输入框事件监听器
    const searchInput = document.getElementById('itemSearchInput');
    if (searchInput) {
        // 使用防抖来避免频繁搜索
        let searchTimeout;
        searchInput.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                filterItems();
            }, 300); // 300ms 防抖延迟
        });
    }

    // 初始化页面输入框事件监听器
    const pageInput = document.getElementById('itemsPageInput');
    if (pageInput) {
        pageInput.addEventListener('keydown', handleItemsPageInput);
    }
}

// 刷新商品列表
async function refreshItems() {
    await refreshItemsData();
    showToast('商品列表已刷新', 'success');
}

// 获取商品信息
async function getAllItemsFromAccount() {
    const cookieSelect = document.getElementById('itemCookieFilter');
    const selectedCookieId = cookieSelect.value;
    const pageNumber = parseInt(document.getElementById('pageNumber').value) || 1;

    if (!selectedCookieId) {
    showToast('请先选择一个账号', 'warning');
                return;
            }

    if (pageNumber < 1) {
    showToast('页码必须大于0', 'warning');
    return;
    }

    // 显示加载状态
    const button = event.target;
    const originalText = button.innerHTML;
    button.innerHTML = '<i class="bi bi-hourglass-split me-1"></i>获取中...';
    button.disabled = true;

    try {
    const response = await fetch(`${apiBase}/items/get-by-page`, {
        method: 'POST',
        headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify({
        cookie_id: selectedCookieId,
        page_number: pageNumber,
        page_size: 20
        })
    });

    if (response.ok) {
        const data = await response.json();
        if (data.success) {
        showToast(`成功获取第${pageNumber}页 ${data.current_count} 个商品，请查看控制台日志`, 'success');
        // 刷新商品列表（保持筛选器选择）
        await refreshItemsData();
        } else {
        showToast(data.message || '获取商品信息失败', 'danger');
        }
    } else {
        throw new Error(`HTTP ${response.status}`);
    }
    } catch (error) {
    console.error('获取商品信息失败:', error);
    showToast('获取商品信息失败', 'danger');
    } finally {
    // 恢复按钮状态
    button.innerHTML = originalText;
    button.disabled = false;
    }
}

// 获取所有页商品信息
async function getAllItemsFromAccountAll() {
    const cookieSelect = document.getElementById('itemCookieFilter');
    const selectedCookieId = cookieSelect.value;

    if (!selectedCookieId) {
    showToast('请先选择一个账号', 'warning');
    return;
    }

    // 显示加载状态
    const button = event.target;
    const originalText = button.innerHTML;
    button.innerHTML = '<i class="bi bi-hourglass-split me-1"></i>获取中...';
    button.disabled = true;

    try {
    const response = await fetch(`${apiBase}/items/get-all-from-account`, {
        method: 'POST',
        headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify({
        cookie_id: selectedCookieId
        })
    });

    if (response.ok) {
        const data = await response.json();
        if (data.success) {
        const message = data.total_pages ?
            `成功获取 ${data.total_count} 个商品（共${data.total_pages}页），请查看控制台日志` :
            `成功获取商品信息，请查看控制台日志`;
        showToast(message, 'success');
        // 刷新商品列表（保持筛选器选择）
        await refreshItemsData();
        } else {
        showToast(data.message || '获取商品信息失败', 'danger');
        }
    } else {
        throw new Error(`HTTP ${response.status}`);
    }
    } catch (error) {
    console.error('获取商品信息失败:', error);
    showToast('获取商品信息失败', 'danger');
    } finally {
    // 恢复按钮状态
    button.innerHTML = originalText;
    button.disabled = false;
    }
}



// 编辑商品详情
async function editItem(cookieId, itemId) {
    try {
    const response = await fetch(`${apiBase}/items/${encodeURIComponent(cookieId)}/${encodeURIComponent(itemId)}`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        const data = await response.json();
        const item = data.item;

        // 填充表单
        document.getElementById('editItemCookieId').value = item.cookie_id;
        document.getElementById('editItemId').value = item.item_id;
        document.getElementById('editItemCookieIdDisplay').value = item.cookie_id;
        document.getElementById('editItemIdDisplay').value = item.item_id;
        document.getElementById('editItemDetail').value = item.item_detail || '';

        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('editItemModal'));
        modal.show();
    } else {
        throw new Error('获取商品详情失败');
    }
    } catch (error) {
    console.error('获取商品详情失败:', error);
    showToast('获取商品详情失败', 'danger');
    }
}

// 保存商品详情
async function saveItemDetail() {
    const cookieId = document.getElementById('editItemCookieId').value;
    const itemId = document.getElementById('editItemId').value;
    const itemDetail = document.getElementById('editItemDetail').value.trim();

    if (!itemDetail) {
    showToast('请输入商品详情', 'warning');
    return;
    }

    try {
    const response = await fetch(`${apiBase}/items/${encodeURIComponent(cookieId)}/${encodeURIComponent(itemId)}`, {
        method: 'PUT',
            headers: {
        'Content-Type': 'application/json',
                'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify({
        item_detail: itemDetail
        })
        });

        if (response.ok) {
        showToast('商品详情更新成功', 'success');

        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('editItemModal'));
        modal.hide();

        // 刷新列表（保持筛选器选择）
        await refreshItemsData();
                } else {
        const error = await response.text();
        showToast(`更新失败: ${error}`, 'danger');
    }
    } catch (error) {
    console.error('更新商品详情失败:', error);
    showToast('更新商品详情失败', 'danger');
    }
}

// 删除商品信息
async function deleteItem(cookieId, itemId, itemTitle) {
    try {
    // 确认删除
    const confirmed = confirm(`确定要删除商品信息吗？\n\n商品ID: ${itemId}\n商品标题: ${itemTitle || '未设置'}\n\n此操作不可撤销！`);
    if (!confirmed) {
        return;
    }

    const response = await fetch(`${apiBase}/items/${encodeURIComponent(cookieId)}/${encodeURIComponent(itemId)}`, {
        method: 'DELETE',
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        showToast('商品信息删除成功', 'success');
        // 刷新列表（保持筛选器选择）
        await refreshItemsData();
    } else {
        const error = await response.text();
        showToast(`删除失败: ${error}`, 'danger');
        }
    } catch (error) {
    console.error('删除商品信息失败:', error);
    showToast('删除商品信息失败', 'danger');
    }
}

// 批量删除商品信息
async function batchDeleteItems() {
    try {
    // 获取所有选中的复选框
    const checkboxes = document.querySelectorAll('input[name="itemCheckbox"]:checked');
    if (checkboxes.length === 0) {
        showToast('请选择要删除的商品', 'warning');
        return;
    }

    // 确认删除
    const confirmed = confirm(`确定要删除选中的 ${checkboxes.length} 个商品信息吗？\n\n此操作不可撤销！`);
    if (!confirmed) {
        return;
    }

    // 构造删除列表
    const itemsToDelete = Array.from(checkboxes).map(checkbox => {
        const row = checkbox.closest('tr');
        return {
        cookie_id: checkbox.dataset.cookieId,
        item_id: checkbox.dataset.itemId
        };
    });

    const response = await fetch(`${apiBase}/items/batch`, {
        method: 'DELETE',
        headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify({ items: itemsToDelete })
    });

    if (response.ok) {
        const result = await response.json();
        showToast(`批量删除完成: 成功 ${result.success_count} 个，失败 ${result.failed_count} 个`, 'success');
        // 刷新列表（保持筛选器选择）
        await refreshItemsData();
    } else {
        const error = await response.text();
        showToast(`批量删除失败: ${error}`, 'danger');
    }
    } catch (error) {
    console.error('批量删除商品信息失败:', error);
    showToast('批量删除商品信息失败', 'danger');
    }
}

// 全选/取消全选
function toggleSelectAll(selectAllCheckbox) {
    const checkboxes = document.querySelectorAll('input[name="itemCheckbox"]');
    checkboxes.forEach(checkbox => {
    checkbox.checked = selectAllCheckbox.checked;
    });
    updateBatchDeleteButton();
}

// 更新全选状态
function updateSelectAllState() {
    const checkboxes = document.querySelectorAll('input[name="itemCheckbox"]');
    const checkedCheckboxes = document.querySelectorAll('input[name="itemCheckbox"]:checked');
    const selectAllCheckbox = document.getElementById('selectAllItems');

    if (checkboxes.length === 0) {
    selectAllCheckbox.checked = false;
    selectAllCheckbox.indeterminate = false;
    } else if (checkedCheckboxes.length === checkboxes.length) {
    selectAllCheckbox.checked = true;
    selectAllCheckbox.indeterminate = false;
    } else if (checkedCheckboxes.length > 0) {
    selectAllCheckbox.checked = false;
    selectAllCheckbox.indeterminate = true;
    } else {
    selectAllCheckbox.checked = false;
    selectAllCheckbox.indeterminate = false;
    }

    updateBatchDeleteButton();
}

// 更新批量删除按钮状态
function updateBatchDeleteButton() {
    const checkedCheckboxes = document.querySelectorAll('input[name="itemCheckbox"]:checked');
    const batchDeleteBtn = document.getElementById('batchDeleteBtn');

    if (checkedCheckboxes.length > 0) {
    batchDeleteBtn.disabled = false;
    batchDeleteBtn.innerHTML = `<i class="bi bi-trash"></i> 批量删除 (${checkedCheckboxes.length})`;
    } else {
    batchDeleteBtn.disabled = true;
    batchDeleteBtn.innerHTML = '<i class="bi bi-trash"></i> 批量删除';
    }
}

// 格式化日期时间
function formatDateTime(dateString) {
    if (!dateString) return '未知';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
}

// HTML转义函数
function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// ================================
// 【日志管理菜单】相关功能
// ================================

window.autoRefreshInterval = null;
window.allLogs = [];
window.filteredLogs = [];

// 刷新日志
async function refreshLogs() {
    try {
    const lines = document.getElementById('logLines').value;

    const response = await fetch(`${apiBase}/logs?lines=${lines}`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        const data = await response.json();
        window.allLogs = data.logs || [];
        window.filteredLogs = window.allLogs; // 不再过滤，直接显示所有日志
        displayLogs();
        updateLogStats();
        showToast('日志已刷新', 'success');
    } else {
        throw new Error(`HTTP ${response.status}`);
    }
    } catch (error) {
    console.error('刷新日志失败:', error);
    showToast('刷新日志失败', 'danger');
    }
}



// 显示日志
function displayLogs() {
    const container = document.getElementById('logContainer');

    if (window.filteredLogs.length === 0) {
    container.innerHTML = `
        <div class="text-center p-4 text-muted">
        <i class="bi bi-file-text fs-1"></i>
        <p class="mt-2">暂无日志数据</p>
        </div>
    `;
    return;
    }

    const logsHtml = window.filteredLogs.map(log => {
    const timestamp = formatLogTimestamp(log.timestamp);
    const levelClass = log.level || 'INFO';

    return `
        <div class="log-entry ${levelClass}">
        <span class="log-timestamp">${timestamp}</span>
        <span class="log-level">[${log.level}]</span>
        <span class="log-source">${log.source}:</span>
        <span class="log-message">${escapeHtml(log.message)}</span>
        </div>
    `;
    }).join('');

    container.innerHTML = logsHtml;

    // 滚动到底部
    container.scrollTop = container.scrollHeight;
}

// 格式化日志时间戳
function formatLogTimestamp(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    fractionalSecondDigits: 3
    });
}

// 更新日志统计信息
function updateLogStats() {
    document.getElementById('logCount').textContent = `${window.filteredLogs.length} 条日志`;
    document.getElementById('lastUpdate').textContent = new Date().toLocaleTimeString('zh-CN');
}

// 清空日志显示
function clearLogsDisplay() {
    window.allLogs = [];
    window.filteredLogs = [];
    document.getElementById('logContainer').innerHTML = `
    <div class="text-center p-4 text-muted">
        <i class="bi bi-file-text fs-1"></i>
        <p class="mt-2">日志显示已清空</p>
    </div>
    `;
    updateLogStats();
    showToast('日志显示已清空', 'info');
}

// 切换自动刷新
function toggleAutoRefresh() {
    const button = document.querySelector('#autoRefreshText');
    const icon = button.previousElementSibling;

    if (window.autoRefreshInterval) {
    // 停止自动刷新
    clearInterval(window.autoRefreshInterval);
    window.autoRefreshInterval = null;
    button.textContent = '开启自动刷新';
    icon.className = 'bi bi-play-circle me-1';
    showToast('自动刷新已停止', 'info');
    } else {
    // 开启自动刷新
    window.autoRefreshInterval = setInterval(refreshLogs, 5000); // 每5秒刷新一次
    button.textContent = '停止自动刷新';
    icon.className = 'bi bi-pause-circle me-1';
    showToast('自动刷新已开启（每5秒）', 'success');

    // 立即刷新一次
    refreshLogs();
    }
}

// 清空服务器日志
async function clearLogsServer() {
    if (!confirm('确定要清空服务器端的所有日志吗？此操作不可恢复！')) {
    return;
    }

    try {
    const response = await fetch(`${apiBase}/logs/clear`, {
        method: 'POST',
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        const data = await response.json();
        if (data.success) {
        window.allLogs = [];
        window.filteredLogs = [];
        displayLogs();
        updateLogStats();
        showToast('服务器日志已清空', 'success');
        } else {
        showToast(data.message || '清空失败', 'danger');
        }
    } else {
        throw new Error(`HTTP ${response.status}`);
    }
    } catch (error) {
    console.error('清空服务器日志失败:', error);
    showToast('清空服务器日志失败', 'danger');
    }
}

// 显示日志统计信息
async function showLogStats() {
    try {
    const response = await fetch(`${apiBase}/logs/stats`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        const data = await response.json();
        if (data.success) {
        const stats = data.stats;

        let statsHtml = `
            <div class="row">
            <div class="col-md-6">
                <h6>总体统计</h6>
                <ul class="list-unstyled">
                <li>总日志数: <strong>${stats.total_logs}</strong></li>
                <li>最大容量: <strong>${stats.max_capacity}</strong></li>
                <li>使用率: <strong>${((stats.total_logs / stats.max_capacity) * 100).toFixed(1)}%</strong></li>
                </ul>
            </div>
            <div class="col-md-6">
                <h6>级别分布</h6>
                <ul class="list-unstyled">
        `;

        for (const [level, count] of Object.entries(stats.level_counts || {})) {
            const percentage = ((count / stats.total_logs) * 100).toFixed(1);
            statsHtml += `<li>${level}: <strong>${count}</strong> (${percentage}%)</li>`;
        }

        statsHtml += `
                </ul>
            </div>
            </div>
            <div class="row mt-3">
            <div class="col-12">
                <h6>来源分布</h6>
                <div class="row">
        `;

        const sources = Object.entries(stats.source_counts || {});
        sources.forEach(([source, count], index) => {
            if (index % 2 === 0) statsHtml += '<div class="col-md-6"><ul class="list-unstyled">';
            const percentage = ((count / stats.total_logs) * 100).toFixed(1);
            statsHtml += `<li>${source}: <strong>${count}</strong> (${percentage}%)</li>`;
            if (index % 2 === 1 || index === sources.length - 1) statsHtml += '</ul></div>';
        });

        statsHtml += `
                </div>
            </div>
            </div>
        `;

        // 显示模态框
        const modalHtml = `
            <div class="modal fade" id="logStatsModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">日志统计信息</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    ${statsHtml}
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
                </div>
            </div>
            </div>
        `;

        // 移除旧的模态框
        const oldModal = document.getElementById('logStatsModal');
        if (oldModal) oldModal.remove();

        // 添加新的模态框
        document.body.insertAdjacentHTML('beforeend', modalHtml);

        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('logStatsModal'));
        modal.show();

        } else {
        showToast(data.message || '获取统计信息失败', 'danger');
        }
    } else {
        throw new Error(`HTTP ${response.status}`);
    }
    } catch (error) {
    console.error('获取日志统计失败:', error);
    showToast('获取日志统计失败', 'danger');
    }
}

// ==================== 导入导出功能 ====================

// 导出关键词
async function exportKeywords() {
    // 检查用户权限（管理员或有auto_reply_manage权限）
    const hasManagePermission = (currentUserInfo && currentUserInfo.is_admin) || 
                               (currentUserPermissions && currentUserPermissions.includes('auto_reply_manage'));
    
    if (!hasManagePermission) {
        showToast('您没有权限执行此操作', 'warning');
        return;
    }

    if (!currentCookieId) {
        showToast('请先选择账号', 'warning');
        return;
    }

    try {
    const response = await fetch(`${apiBase}/keywords-export/${currentCookieId}`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        // 创建下载链接
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;

        // 根据当前账号是否有数据来设置文件名和提示
        const currentKeywords = keywordsData[currentCookieId] || [];
        const hasData = currentKeywords.length > 0;

        if (hasData) {
        a.download = `keywords_${currentCookieId}_${new Date().getTime()}.xlsx`;
        showToast('关键词导出成功！', 'success');
        } else {
        a.download = `keywords_template_${currentCookieId}_${new Date().getTime()}.xlsx`;
        showToast('导入模板导出成功！模板中包含示例数据供参考', 'success');
        }

        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    } else {
        const error = await response.json();
        showToast(`导出失败: ${error.detail}`, 'error');
    }
    } catch (error) {
    console.error('导出关键词失败:', error);
    showToast('导出关键词失败', 'error');
    }
}

// 显示导入模态框


// ========================= 账号添加相关函数 =========================

// 切换手动输入表单显示/隐藏
function toggleManualInput() {
    const manualForm = document.getElementById('manualInputForm');
    if (manualForm.style.display === 'none') {
    manualForm.style.display = 'block';
    // 清空表单
    document.getElementById('addForm').reset();
    } else {
    manualForm.style.display = 'none';
    }
}

// ========================= 扫码登录相关函数 =========================

let qrCodeCheckInterval = null;
let qrCodeSessionId = null;

// 显示扫码登录模态框
function showQRCodeLogin() {
    const modal = new bootstrap.Modal(document.getElementById('qrCodeLoginModal'));
    modal.show();

    // 模态框显示后生成二维码
    modal._element.addEventListener('shown.bs.modal', function () {
    generateQRCode();
    });

    // 模态框关闭时清理定时器
    modal._element.addEventListener('hidden.bs.modal', function () {
    clearQRCodeCheck();
    });
}

// 刷新二维码（兼容旧函数名）
async function refreshQRCode() {
    await generateQRCode();
}

// 生成二维码
async function generateQRCode() {
    try {
    showQRCodeLoading();

    const response = await fetch(`${apiBase}/qr-login/generate`, {
        method: 'POST',
        headers: {
        'Authorization': `Bearer ${authToken}`,
        'Content-Type': 'application/json'
        }
    });

    if (response.ok) {
        const data = await response.json();
        if (data.success) {
        qrCodeSessionId = data.session_id;
        showQRCodeImage(data.qr_code_url);
        startQRCodeCheck();
        } else {
        showQRCodeError(data.message || '生成二维码失败');
        }
    } else {
        showQRCodeError('生成二维码失败');
    }
    } catch (error) {
    console.error('生成二维码失败:', error);
    showQRCodeError('网络错误，请重试');
    }
}

// 显示二维码加载状态
function showQRCodeLoading() {
    document.getElementById('qrCodeContainer').style.display = 'block';
    document.getElementById('qrCodeImage').style.display = 'none';
    document.getElementById('statusText').textContent = '正在生成二维码，请耐心等待...';
    document.getElementById('statusSpinner').style.display = 'none';

    // 隐藏验证容器
    const verificationContainer = document.getElementById('verificationContainer');
    if (verificationContainer) {
    verificationContainer.style.display = 'none';
    }
}

// 显示二维码图片
function showQRCodeImage(qrCodeUrl) {
    document.getElementById('qrCodeContainer').style.display = 'none';
    document.getElementById('qrCodeImage').style.display = 'block';
    document.getElementById('qrCodeImg').src = qrCodeUrl;
    document.getElementById('statusText').textContent = '等待扫码...';
    document.getElementById('statusSpinner').style.display = 'none';
}

// 显示二维码错误
function showQRCodeError(message) {
    document.getElementById('qrCodeContainer').innerHTML = `
    <div class="text-danger">
        <i class="bi bi-exclamation-triangle fs-1 mb-3"></i>
        <p>${message}</p>
    </div>
    `;
    document.getElementById('qrCodeImage').style.display = 'none';
    document.getElementById('statusText').textContent = '生成失败';
    document.getElementById('statusSpinner').style.display = 'none';
}

// 开始检查二维码状态
function startQRCodeCheck() {
    if (qrCodeCheckInterval) {
    clearInterval(qrCodeCheckInterval);
    }

    document.getElementById('statusSpinner').style.display = 'inline-block';
    document.getElementById('statusText').textContent = '等待扫码...';

    qrCodeCheckInterval = setInterval(checkQRCodeStatus, 2000); // 每2秒检查一次
}

// 检查二维码状态
async function checkQRCodeStatus() {
    if (!qrCodeSessionId) return;

    try {
    const response = await fetch(`${apiBase}/qr-login/check/${qrCodeSessionId}`, {
        headers: {
        'Authorization': `Bearer ${authToken}`
        }
    });

    if (response.ok) {
        const data = await response.json();

        switch (data.status) {
        case 'waiting':
            document.getElementById('statusText').textContent = '等待扫码...';
            break;
        case 'scanned':
            document.getElementById('statusText').textContent = '已扫码，请在手机上确认...';
            break;
        case 'success':
            document.getElementById('statusText').textContent = '登录成功！';
            document.getElementById('statusSpinner').style.display = 'none';
            clearQRCodeCheck();
            handleQRCodeSuccess(data);
            break;
        case 'expired':
            document.getElementById('statusText').textContent = '二维码已过期';
            document.getElementById('statusSpinner').style.display = 'none';
            clearQRCodeCheck();
            showQRCodeError('二维码已过期，请刷新重试');
            break;
        case 'cancelled':
            document.getElementById('statusText').textContent = '用户取消登录';
            document.getElementById('statusSpinner').style.display = 'none';
            clearQRCodeCheck();
            break;
        case 'verification_required':
            document.getElementById('statusText').textContent = '需要手机验证';
            document.getElementById('statusSpinner').style.display = 'none';
            clearQRCodeCheck();
            showVerificationRequired(data);
            break;
        }
    }
    } catch (error) {
    console.error('检查二维码状态失败:', error);
    }
}

// 显示需要验证的提示
function showVerificationRequired(data) {
    if (data.verification_url) {
    // 隐藏二维码区域
    document.getElementById('qrCodeContainer').style.display = 'none';
    document.getElementById('qrCodeImage').style.display = 'none';

    // 显示验证提示
    const verificationHtml = `
        <div class="text-center">
        <div class="mb-4">
            <i class="bi bi-shield-exclamation text-warning" style="font-size: 4rem;"></i>
        </div>
        <h5 class="text-warning mb-3">账号需要手机验证</h5>
        <div class="alert alert-warning border-0 mb-4">
            <i class="bi bi-info-circle me-2"></i>
            <strong>检测到账号存在风控，需要进行手机验证才能完成登录</strong>
        </div>
        <div class="mb-4">
            <p class="text-muted mb-3">请点击下方按钮，在新窗口中完成手机验证：</p>
            <a href="${data.verification_url}" target="_blank" class="btn btn-warning btn-lg">
            <i class="bi bi-phone me-2"></i>
            打开手机验证页面
            </a>
        </div>
        <div class="alert alert-info border-0">
            <i class="bi bi-lightbulb me-2"></i>
            <small>
            <strong>验证步骤：</strong><br>
            1. 点击上方按钮打开验证页面<br>
            2. 按照页面提示完成手机验证<br>
            3. 验证完成后，重新扫码登录
            </small>
        </div>
        </div>
    `;

    // 创建验证提示容器
    let verificationContainer = document.getElementById('verificationContainer');
    if (!verificationContainer) {
        verificationContainer = document.createElement('div');
        verificationContainer.id = 'verificationContainer';
        document.querySelector('#qrCodeLoginModal .modal-body').appendChild(verificationContainer);
    }

    verificationContainer.innerHTML = verificationHtml;
    verificationContainer.style.display = 'block';

    // 显示Toast提示
    showToast('账号需要手机验证，请按照提示完成验证', 'warning');
    }
}

// 处理扫码成功
function handleQRCodeSuccess(data) {
    if (data.account_info) {
    const { account_id, is_new_account } = data.account_info;

    if (is_new_account) {
        showToast(`新账号添加成功！账号ID: ${account_id}`, 'success');
    } else {
        showToast(`账号Cookie已更新！账号ID: ${account_id}`, 'success');
    }

    // 关闭模态框
    setTimeout(() => {
        const modal = bootstrap.Modal.getInstance(document.getElementById('qrCodeLoginModal'));
        modal.hide();

        // 刷新账号列表
        loadCookies();
    }, 2000);
    }
}

// 清理二维码检查
function clearQRCodeCheck() {
    if (qrCodeCheckInterval) {
    clearInterval(qrCodeCheckInterval);
    qrCodeCheckInterval = null;
    }
    qrCodeSessionId = null;
}

// 刷新二维码
function refreshQRCode() {
    clearQRCodeCheck();
    generateQRCode();
}

// ==================== 商品专属回复语管理功能 ====================

// 显示商品专属回复语模态框
async function showItemExclusiveReplyModal(itemId, event) {
    // 阻止事件冒泡
    if (event) {
        event.stopPropagation();
    }

    if (!currentCookieId) {
        showToast('请先选择账号', 'warning');
        return;
    }

    // 设置商品ID
    document.getElementById('exclusiveReplyItemId').value = itemId;

    // 清空表单
    document.getElementById('exclusiveReplyContent').value = '';
    document.getElementById('exclusiveReplyEnabled').checked = true;

    // 隐藏当前专属回复语显示区域
    document.getElementById('currentExclusiveReply').style.display = 'none';

    try {
        // 获取现有的专属回复语
        const response = await fetch(`${apiBase}/item-exclusive-reply/${currentCookieId}/${itemId}`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });

        if (response.ok) {
            const data = await response.json();
            if (data) {
                // 显示现有专属回复语
                document.getElementById('currentExclusiveReplyContent').textContent = data.reply_content;
                document.getElementById('currentExclusiveReplyStatus').textContent = data.enabled ? '启用' : '禁用';
                document.getElementById('currentExclusiveReplyStatus').className = data.enabled ? 'text-success' : 'text-danger';
                document.getElementById('currentExclusiveReplyTime').textContent = formatDateTime(data.updated_at);
                document.getElementById('currentExclusiveReply').style.display = 'block';

                // 填充表单
                document.getElementById('exclusiveReplyContent').value = data.reply_content;
                document.getElementById('exclusiveReplyEnabled').checked = data.enabled;
            }
        }
    } catch (error) {
        console.error('获取专属回复语失败:', error);
    }

    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('itemExclusiveReplyModal'));
    modal.show();
}

// 保存商品专属回复语
async function saveItemExclusiveReply() {
    const itemId = document.getElementById('exclusiveReplyItemId').value;
    const replyContent = document.getElementById('exclusiveReplyContent').value.trim();
    const enabled = document.getElementById('exclusiveReplyEnabled').checked;

    if (!replyContent) {
        showToast('请输入专属回复内容', 'warning');
        return;
    }

    try {
        const response = await fetch(`${apiBase}/item-exclusive-reply/${currentCookieId}/${itemId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${authToken}`
            },
            body: JSON.stringify({
                reply_content: replyContent,
                enabled: enabled
            })
        });

        if (response.ok) {
            showToast('专属回复语保存成功', 'success');
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('itemExclusiveReplyModal'));
            modal.hide();
        } else {
            const errorData = await response.json();
            showToast(`保存失败: ${errorData.detail || '未知错误'}`, 'error');
        }
    } catch (error) {
        console.error('保存专属回复语失败:', error);
        showToast('保存失败，请检查网络连接', 'error');
    }
}

// 删除商品专属回复语
async function deleteItemExclusiveReply() {
    const itemId = document.getElementById('exclusiveReplyItemId').value;

    if (!confirm('确定要删除这个商品的专属回复语吗？此操作无法撤销！')) {
        return;
    }

    try {
        const response = await fetch(`${apiBase}/item-exclusive-reply/${currentCookieId}/${itemId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });

        if (response.ok) {
            showToast('专属回复语删除成功', 'success');
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('itemExclusiveReplyModal'));
            modal.hide();
        } else {
            const errorData = await response.json();
            showToast(`删除失败: ${errorData.detail || '未知错误'}`, 'error');
        }
    } catch (error) {
        console.error('删除专属回复语失败:', error);
        showToast('删除失败，请检查网络连接', 'error');
    }
}

// ==================== 图片关键词管理功能 ====================

// 显示添加图片关键词模态框
function showAddImageKeywordModal() {
    // 检查用户权限（管理员或有auto_reply_manage权限）
    const hasManagePermission = (currentUserInfo && currentUserInfo.is_admin) || 
                               (currentUserPermissions && currentUserPermissions.includes('auto_reply_manage'));
    
    if (!hasManagePermission) {
        showToast('您没有权限执行此操作', 'warning');
        return;
    }

    if (!currentCookieId) {
        showToast('请先选择账号', 'warning');
        return;
    }

    // 加载商品列表到图片关键词模态框
    loadItemsListForImageKeyword();

    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('addImageKeywordModal'));
    modal.show();

    // 清空表单
    document.getElementById('imageKeyword').value = '';
    document.getElementById('imageItemIdSelect').value = '';
    document.getElementById('imageFile').value = '';
    hideImagePreview();
}

// 为图片关键词模态框加载商品列表
async function loadItemsListForImageKeyword() {
    try {
        const response = await fetch(`${apiBase}/items/${currentCookieId}`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });

        if (response.ok) {
            const data = await response.json();
            const items = data.items || [];

            // 更新商品选择下拉框
            const selectElement = document.getElementById('imageItemIdSelect');
            if (selectElement) {
                // 清空现有选项（保留第一个默认选项）
                selectElement.innerHTML = '<option value="">选择商品或留空表示通用关键词</option>';

                // 添加商品选项
                items.forEach(item => {
                    const option = document.createElement('option');
                    option.value = item.item_id;
                    option.textContent = `${item.item_id} - ${item.item_title}`;
                    selectElement.appendChild(option);
                });
            }

            console.log(`为图片关键词加载了 ${items.length} 个商品到选择列表`);
        } else {
            console.warn('加载商品列表失败:', response.status);
        }
    } catch (error) {
        console.error('加载商品列表时发生错误:', error);
    }
}

// 处理图片文件选择事件监听器
function initImageKeywordEventListeners() {
    const imageFileInput = document.getElementById('imageFile');
    if (imageFileInput && !imageFileInput.hasEventListener) {
        imageFileInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                // 验证文件类型
                if (!file.type.startsWith('image/')) {
                    showToast('请选择图片文件', 'warning');
                    e.target.value = '';
                    hideImagePreview();
                    return;
                }

                // 验证文件大小（5MB）
                if (file.size > 5 * 1024 * 1024) {
                    showToast('❌ 图片文件大小不能超过 5MB，当前文件大小：' + (file.size / 1024 / 1024).toFixed(1) + 'MB', 'warning');
                    e.target.value = '';
                    hideImagePreview();
                    return;
                }

                // 验证图片尺寸
                validateImageDimensions(file, e.target);
            } else {
                hideImagePreview();
            }
        });
        imageFileInput.hasEventListener = true;
    }
}

// 验证图片尺寸
function validateImageDimensions(file, inputElement) {
    const img = new Image();
    const url = URL.createObjectURL(file);

    img.onload = function() {
        const width = this.naturalWidth;
        const height = this.naturalHeight;

        // 释放对象URL
        URL.revokeObjectURL(url);

        // 检查图片尺寸
        const maxDimension = 4096;
        const maxPixels = 8 * 1024 * 1024; // 8M像素
        const totalPixels = width * height;

        if (width > maxDimension || height > maxDimension) {
            showToast(`❌ 图片尺寸过大：${width}x${height}，最大允许：${maxDimension}x${maxDimension}像素`, 'warning');
            inputElement.value = '';
            hideImagePreview();
            return;
        }

        if (totalPixels > maxPixels) {
            showToast(`❌ 图片像素总数过大：${(totalPixels / 1024 / 1024).toFixed(1)}M像素，最大允许：8M像素`, 'warning');
            inputElement.value = '';
            hideImagePreview();
            return;
        }

        // 尺寸检查通过，显示预览和提示信息
        showImagePreview(file);

        // 如果图片较大，提示会被压缩
        if (width > 2048 || height > 2048) {
            showToast(`ℹ️ 图片尺寸较大（${width}x${height}），上传时将自动压缩以优化性能`, 'info');
        } else {
            showToast(`✅ 图片尺寸合适（${width}x${height}），可以上传`, 'success');
        }
    };

    img.onerror = function() {
        URL.revokeObjectURL(url);
        showToast('❌ 无法读取图片文件，请选择有效的图片', 'warning');
        inputElement.value = '';
        hideImagePreview();
    };

    img.src = url;
}

// 显示图片预览
function showImagePreview(file) {
    const reader = new FileReader();
    reader.onload = function(e) {
        const previewContainer = document.getElementById('imagePreview');
        const previewImg = document.getElementById('previewImg');

        previewImg.src = e.target.result;
        previewContainer.style.display = 'block';
    };
    reader.readAsDataURL(file);
}

// 隐藏图片预览
function hideImagePreview() {
    const previewContainer = document.getElementById('imagePreview');
    if (previewContainer) {
        previewContainer.style.display = 'none';
    }
}

// 添加图片关键词
async function addImageKeyword() {
    const keyword = document.getElementById('imageKeyword').value.trim();
    const itemId = document.getElementById('imageItemIdSelect').value.trim();
    const fileInput = document.getElementById('imageFile');
    const file = fileInput.files[0];

    if (!keyword) {
        showToast('请填写关键词', 'warning');
        return;
    }

    if (!file) {
        showToast('请选择图片文件', 'warning');
        return;
    }

    if (!currentCookieId) {
        showToast('请先选择账号', 'warning');
        return;
    }

    try {
        toggleLoading(true);

        // 创建FormData对象
        const formData = new FormData();
        formData.append('keyword', keyword);
        formData.append('item_id', itemId || '');
        formData.append('image', file);

        const response = await fetch(`${apiBase}/keywords/${currentCookieId}/image`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${authToken}`
            },
            body: formData
        });

        if (response.ok) {
            showToast(`✨ 图片关键词 "${keyword}" 添加成功！`, 'success');

            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('addImageKeywordModal'));
            modal.hide();

            // 只刷新关键词列表，不重新加载整个界面
            await refreshKeywordsList();
        } else {
            try {
                const errorData = await response.json();
                let errorMessage = errorData.detail || '图片关键词添加失败';

                // 根据不同的错误类型提供更友好的提示
                if (errorMessage.includes('关键词') && (errorMessage.includes('已存在') || errorMessage.includes('重复'))) {
                    errorMessage = `❌ 关键词重复：${errorMessage}`;
                } else if (errorMessage.includes('图片尺寸过大')) {
                    errorMessage = '❌ 图片尺寸过大，请选择尺寸较小的图片（建议不超过4096x4096像素）';
                } else if (errorMessage.includes('图片像素总数过大')) {
                    errorMessage = '❌ 图片像素总数过大，请选择分辨率较低的图片';
                } else if (errorMessage.includes('图片数据验证失败')) {
                    errorMessage = '❌ 图片格式不支持或文件损坏，请选择JPG、PNG、GIF格式的图片';
                } else if (errorMessage.includes('图片保存失败')) {
                    errorMessage = '❌ 图片保存失败，请检查图片格式和大小后重试';
                } else if (errorMessage.includes('文件大小超过限制')) {
                    errorMessage = '❌ 图片文件过大，请选择小于5MB的图片';
                } else if (errorMessage.includes('不支持的图片格式')) {
                    errorMessage = '❌ 不支持的图片格式，请选择JPG、PNG、GIF格式的图片';
                } else if (response.status === 413) {
                    errorMessage = '❌ 图片文件过大，请选择小于5MB的图片';
                } else if (response.status === 400) {
                    errorMessage = `❌ 请求参数错误：${errorMessage}`;
                } else if (response.status === 500) {
                    errorMessage = '❌ 服务器内部错误，请稍后重试';
                }

                console.error('图片关键词添加失败:', errorMessage);
                showToast(errorMessage, 'danger');
            } catch (e) {
                // 如果不是JSON格式，使用文本
                const errorText = await response.text();
                console.error('图片关键词添加失败:', errorText);

                let friendlyMessage = '图片关键词添加失败';
                if (response.status === 413) {
                    friendlyMessage = '❌ 图片文件过大，请选择小于5MB的图片';
                } else if (response.status === 400) {
                    friendlyMessage = '❌ 图片格式不正确或参数错误，请检查后重试';
                } else if (response.status === 500) {
                    friendlyMessage = '❌ 服务器内部错误，请稍后重试';
                }

                showToast(friendlyMessage, 'danger');
            }
        }
    } catch (error) {
        console.error('添加图片关键词失败:', error);
        showToast('添加图片关键词失败', 'danger');
    } finally {
        toggleLoading(false);
    }
}

// 显示图片模态框
function showImageModal(imageUrl) {
    // 创建模态框HTML
    const modalHtml = `
        <div class="modal fade" id="imageViewModal" tabindex="-1">
            <div class="modal-dialog modal-lg modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">图片预览</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body text-center">
                        <img src="${imageUrl}" alt="关键词图片" style="max-width: 100%; max-height: 70vh; border-radius: 8px;">
                    </div>
                </div>
            </div>
        </div>
    `;

    // 移除已存在的模态框
    const existingModal = document.getElementById('imageViewModal');
    if (existingModal) {
        existingModal.remove();
    }

    // 添加新模态框
    document.body.insertAdjacentHTML('beforeend', modalHtml);

    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('imageViewModal'));
    modal.show();

    // 模态框关闭后移除DOM元素
    document.getElementById('imageViewModal').addEventListener('hidden.bs.modal', function() {
        this.remove();
    });
}

// 编辑图片关键词（不允许修改）
function editImageKeyword(index) {
    // 检查用户权限（管理员或有auto_reply_manage权限）
    const hasManagePermission = (currentUserInfo && currentUserInfo.is_admin) || 
                               (currentUserPermissions && currentUserPermissions.includes('auto_reply_manage'));
    
    if (!hasManagePermission) {
        showToast('您没有权限执行此操作', 'warning');
        return;
    }

    showToast('图片关键词不允许修改，请删除后重新添加', 'warning');
}

// 修改导出关键词函数，使用后端导出API
async function exportKeywords() {
    // 检查用户权限（管理员或有auto_reply_manage权限）
    const hasManagePermission = (currentUserInfo && currentUserInfo.is_admin) || 
                               (currentUserPermissions && currentUserPermissions.includes('auto_reply_manage'));
    
    if (!hasManagePermission) {
        showToast('您没有权限执行此操作', 'warning');
        return;
    }

    if (!currentCookieId) {
        showToast('请先选择账号', 'warning');
        return;
    }

    try {
        toggleLoading(true);

        // 使用后端导出API
        const response = await fetch(`${apiBase}/keywords-export/${currentCookieId}`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });

        if (response.ok) {
            // 获取文件blob
            const blob = await response.blob();

            // 从响应头获取文件名
            const contentDisposition = response.headers.get('Content-Disposition');
            let fileName = `关键词数据_${currentCookieId}_${new Date().toISOString().slice(0, 10)}.xlsx`;

            if (contentDisposition) {
                const fileNameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)/);
                if (fileNameMatch) {
                    fileName = decodeURIComponent(fileNameMatch[1]);
                }
            }

            // 创建下载链接
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = fileName;
            document.body.appendChild(a);
            a.click();

            // 清理
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);

            showToast('✅ 关键词导出成功', 'success');
        } else {
            const errorText = await response.text();
            console.error('导出关键词失败:', errorText);
            showToast('导出关键词失败', 'danger');
        }
    } catch (error) {
        console.error('导出关键词失败:', error);
        showToast('导出关键词失败', 'danger');
    } finally {
        toggleLoading(false);
    }
}

// ==================== 备注管理功能 ====================

// 编辑备注
function editRemark(cookieId, currentRemark) {
    console.log('editRemark called:', cookieId, currentRemark); // 调试信息
    const remarkCell = document.querySelector(`[data-cookie-id="${cookieId}"] .remark-display`);
    if (!remarkCell) {
        console.log('remarkCell not found'); // 调试信息
        return;
    }

    // 创建输入框
    const input = document.createElement('input');
    input.type = 'text';
    input.className = 'form-control form-control-sm';
    input.value = currentRemark || '';
    input.placeholder = '请输入备注...';
    input.style.fontSize = '0.875rem';
    input.maxLength = 100; // 限制备注长度

    // 保存原始内容和原始值
    const originalContent = remarkCell.innerHTML;
    const originalValue = currentRemark || '';

    // 标记是否已经进行了编辑
    let hasChanged = false;
    let isProcessing = false; // 防止重复处理

    // 替换为输入框
    remarkCell.innerHTML = '';
    remarkCell.appendChild(input);

    // 监听输入变化
    input.addEventListener('input', () => {
        hasChanged = input.value.trim() !== originalValue;
    });

    // 保存函数
    const saveRemark = async () => {
        console.log('saveRemark called, isProcessing:', isProcessing, 'hasChanged:', hasChanged); // 调试信息
        if (isProcessing) return; // 防止重复调用

        const newRemark = input.value.trim();
        console.log('newRemark:', newRemark, 'originalValue:', originalValue); // 调试信息

        // 如果没有变化，直接恢复显示
        if (!hasChanged || newRemark === originalValue) {
            console.log('No changes detected, restoring original content'); // 调试信息
            remarkCell.innerHTML = originalContent;
            return;
        }

        isProcessing = true;

        try {
            const response = await fetch(`${apiBase}/cookies/${cookieId}/remark`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${authToken}`
                },
                body: JSON.stringify({ remark: newRemark })
            });

            if (response.ok) {
                // 更新显示
                remarkCell.innerHTML = `
                    <span class="remark-display" onclick="editRemark('${cookieId}', '${newRemark.replace(/'/g, '&#39;')}')" title="点击编辑备注" style="cursor: pointer; color: #6c757d; font-size: 0.875rem;">
                        ${newRemark || '<i class="bi bi-plus-circle text-muted"></i> 添加备注'}
                    </span>
                `;
                showToast('备注更新成功', 'success');
            } else {
                const errorData = await response.json();
                showToast(`备注更新失败: ${errorData.detail || '未知错误'}`, 'danger');
                // 恢复原始内容
                remarkCell.innerHTML = originalContent;
            }
        } catch (error) {
            console.error('更新备注失败:', error);
            showToast('备注更新失败', 'danger');
            // 恢复原始内容
            remarkCell.innerHTML = originalContent;
        } finally {
            isProcessing = false;
        }
    };

    // 取消函数
    const cancelEdit = () => {
        if (isProcessing) return;
        remarkCell.innerHTML = originalContent;
    };

    // 延迟绑定blur事件，避免立即触发
    setTimeout(() => {
        input.addEventListener('blur', saveRemark);
    }, 100);

    // 绑定键盘事件
    input.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            saveRemark();
        } else if (e.key === 'Escape') {
            e.preventDefault();
            cancelEdit();
        }
    });

    // 聚焦并选中文本
    input.focus();
    input.select();
}

// 编辑通知wxid
function editNotificationWxid(cookieId, currentWxid) {
    console.log('editNotificationWxid called:', cookieId, currentWxid); // 调试信息
    const wxidCell = document.querySelector(`[data-cookie-id="${cookieId}"] .notification-wxid-display`);
    if (!wxidCell) {
        console.log('wxidCell not found'); // 调试信息
        return;
    }

    // 创建输入框
    const input = document.createElement('input');
    input.type = 'text';
    input.className = 'form-control form-control-sm';
    input.value = currentWxid || '';
    input.placeholder = '请输入微信ID...';
    input.style.fontSize = '0.875rem';
    input.maxLength = 50;

    // 保存原始内容和原始值
    const originalContent = wxidCell.innerHTML;
    const originalValue = currentWxid || '';

    // 标记是否已经进行了编辑
    let hasChanged = false;
    let isProcessing = false; // 防止重复处理

    // 替换为输入框
    wxidCell.innerHTML = '';
    wxidCell.appendChild(input);

    // 监听输入变化
    input.addEventListener('input', function() {
        hasChanged = input.value.trim() !== originalValue;
    });

    // 处理保存逻辑
    const saveWxid = async function() {
        if (isProcessing) return;
        isProcessing = true;

        const newWxid = input.value.trim();

        try {
            const response = await fetch(`${apiBase}/cookies/${cookieId}/notification-wxid`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${authToken}`
                },
                body: JSON.stringify({ notification_wxid: newWxid })
            });

            if (response.ok) {
                showToast('通知wxid更新成功', 'success');
                // 更新显示内容
                wxidCell.innerHTML = `<span class="notification-wxid-display" onclick="editNotificationWxid('${cookieId}', '${newWxid.replace(/'/g, '&#39;')}')" title="点击编辑通知wxid" style="cursor: pointer; color: #6c757d; font-size: 0.875rem;">
                    ${newWxid ? '<i class="bi bi-wechat text-success me-1"></i>' + newWxid : '<i class="bi bi-plus-circle text-muted"></i> 设置wxid'}
                </span>`;
            } else {
                const errorData = await response.json();
                showToast(`更新失败: ${errorData.detail}`, 'error');
                // 恢复原始内容
                wxidCell.innerHTML = originalContent;
            }
        } catch (error) {
            console.error('更新通知wxid失败:', error);
            showToast('更新失败，请检查网络连接', 'error');
            // 恢复原始内容
            wxidCell.innerHTML = originalContent;
        } finally {
            isProcessing = false;
        }
    };

    // 处理取消逻辑
    const cancelEdit = function() {
        if (isProcessing) return;
        wxidCell.innerHTML = originalContent;
    };

    // 监听键盘事件
    input.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            saveWxid();
        } else if (e.key === 'Escape') {
            e.preventDefault();
            cancelEdit();
        }
    });

    // 监听失去焦点事件
    input.addEventListener('blur', function() {
        // 延迟执行，避免与点击事件冲突
        setTimeout(() => {
            if (hasChanged && !isProcessing) {
                saveWxid();
            } else if (!isProcessing) {
                cancelEdit();
            }
        }, 100);
    });

    // 聚焦并选中文本
    input.focus();
    if (currentWxid) {
        input.select();
    }
}

// 编辑暂停时间
function editPauseDuration(cookieId, currentDuration) {
    console.log('editPauseDuration called:', cookieId, currentDuration); // 调试信息
    const pauseCell = document.querySelector(`[data-cookie-id="${cookieId}"] .pause-duration-display`);
    if (!pauseCell) {
        console.log('pauseCell not found'); // 调试信息
        return;
    }

    // 创建输入框
    const input = document.createElement('input');
    input.type = 'number';
    input.className = 'form-control form-control-sm';
    input.value = currentDuration || 10;
    input.placeholder = '请输入暂停时间...';
    input.style.fontSize = '0.875rem';
    input.min = 1;
    input.max = 60;
    input.step = 1;

    // 保存原始内容和原始值
    const originalContent = pauseCell.innerHTML;
    const originalValue = currentDuration || 10;

    // 标记是否已经进行了编辑
    let hasChanged = false;
    let isProcessing = false; // 防止重复处理

    // 替换为输入框
    pauseCell.innerHTML = '';
    pauseCell.appendChild(input);

    // 监听输入变化
    input.addEventListener('input', () => {
        const newValue = parseInt(input.value) || 10;
        hasChanged = newValue !== originalValue;
    });

    // 保存函数
    const savePauseDuration = async () => {
        console.log('savePauseDuration called, isProcessing:', isProcessing, 'hasChanged:', hasChanged); // 调试信息
        if (isProcessing) return; // 防止重复调用

        const newDuration = parseInt(input.value) || 10;
        console.log('newDuration:', newDuration, 'originalValue:', originalValue); // 调试信息

        // 验证范围
        if (newDuration < 1 || newDuration > 60) {
            showToast('暂停时间必须在1-60分钟之间', 'warning');
            input.focus();
            return;
        }

        // 如果没有变化，直接恢复显示
        if (!hasChanged || newDuration === originalValue) {
            console.log('No changes detected, restoring original content'); // 调试信息
            pauseCell.innerHTML = originalContent;
            return;
        }

        isProcessing = true;

        try {
            const response = await fetch(`${apiBase}/cookies/${cookieId}/pause-duration`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${authToken}`
                },
                body: JSON.stringify({ pause_duration: newDuration })
            });

            if (response.ok) {
                // 更新显示
                pauseCell.innerHTML = `
                    <span class="pause-duration-display" onclick="editPauseDuration('${cookieId}', ${newDuration})" title="点击编辑暂停时间" style="cursor: pointer; color: #6c757d; font-size: 0.875rem;">
                        <i class="bi bi-clock me-1"></i>${newDuration}分钟
                    </span>
                `;
                showToast('暂停时间更新成功', 'success');
            } else {
                const errorData = await response.json();
                showToast(`暂停时间更新失败: ${errorData.detail || '未知错误'}`, 'danger');
                // 恢复原始内容
                pauseCell.innerHTML = originalContent;
            }
        } catch (error) {
            console.error('更新暂停时间失败:', error);
            showToast('暂停时间更新失败', 'danger');
            // 恢复原始内容
            pauseCell.innerHTML = originalContent;
        } finally {
            isProcessing = false;
        }
    };

    // 取消函数
    const cancelEdit = () => {
        if (isProcessing) return;
        pauseCell.innerHTML = originalContent;
    };

    // 延迟绑定blur事件，避免立即触发
    setTimeout(() => {
        input.addEventListener('blur', savePauseDuration);
    }, 100);

    // 绑定键盘事件
    input.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            savePauseDuration();
        } else if (e.key === 'Escape') {
            e.preventDefault();
            cancelEdit();
        }
    });

    // 聚焦并选中文本
    input.focus();
    input.select();
}

// ==================== 工具提示初始化 ====================

// 初始化工具提示
function initTooltips() {
    // 初始化所有工具提示
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
}

// ==================== 系统设置功能 ====================

// 绑定系统设置相关事件
function bindSystemSettingsEvents() {
    console.log('开始绑定系统设置事件');
    
    // 绑定关键词未匹配回复表单事件
    const unmatchReplyForm = document.getElementById('unmatchReplyForm');
    if (unmatchReplyForm) {
        unmatchReplyForm.removeEventListener('submit', handleUnmatchReplySubmit);
        unmatchReplyForm.addEventListener('submit', handleUnmatchReplySubmit);
        console.log('关键词未匹配回复表单事件已绑定');
    }
    
    // 绑定门店引导话术表单事件
    const storeGuideForm = document.getElementById('storeGuideForm');
    if (storeGuideForm) {
        storeGuideForm.removeEventListener('submit', handleStoreGuideSubmit);
        storeGuideForm.addEventListener('submit', handleStoreGuideSubmit);
        console.log('门店引导话术表单事件已绑定');
    } else {
        console.log('门店引导话术表单未找到，可能页面尚未加载');
    }

}

// 处理关键词未匹配回复表单提交
async function handleUnmatchReplySubmit(e) {
    e.preventDefault();
    await updateUnmatchReplySettings();
}

// 处理门店引导话术表单提交
async function handleStoreGuideSubmit(e) {
    console.log('门店引导话术表单提交事件被触发');
    e.preventDefault();
    await updateStoreGuideSettings();
}



// 加载系统设置
async function loadSystemSettings() {
    console.log('加载系统设置');

    // 通过验证接口获取用户信息（更可靠）
    try {
        const response = await fetch(`${apiBase}/verify`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });

        if (response.ok) {
            const result = await response.json();
            const isAdmin = result.is_admin === true;

            console.log('用户信息:', result, '是否管理员:', isAdmin);

            // 显示/隐藏注册设置（仅管理员可见）
            const registrationSettings = document.getElementById('registration-settings');
            if (registrationSettings) {
                registrationSettings.style.display = isAdmin ? 'block' : 'none';
            }

            // 如果是管理员，加载注册设置
            if (isAdmin) {
                await loadRegistrationSettings();
            }
        }
    } catch (error) {
        console.error('获取用户信息失败:', error);
        // 出错时隐藏管理员功能
        const registrationSettings = document.getElementById('registration-settings');
        if (registrationSettings) {
            registrationSettings.style.display = 'none';
        }
    }

    // 加载各项设置数据
    await loadUnmatchReplySettings();
    await loadStoreGuideSettings();
    await loadDelayedGuideSettings();
    
    // 重新绑定事件（确保在页面切换时也能正常工作）
    setTimeout(() => {
        bindSystemSettingsEvents();
    }, 100);
}

// 加载注册设置
async function loadRegistrationSettings() {
    try {
        const response = await fetch('/registration-status');
        if (response.ok) {
            const data = await response.json();
            const checkbox = document.getElementById('registrationEnabled');
            if (checkbox) {
                checkbox.checked = data.enabled;
            }
        }
    } catch (error) {
        console.error('加载注册设置失败:', error);
        showToast('加载注册设置失败', 'danger');
    }
}

// 更新注册设置
async function updateRegistrationSettings() {
    const checkbox = document.getElementById('registrationEnabled');
    const statusDiv = document.getElementById('registrationStatus');
    const statusText = document.getElementById('registrationStatusText');

    if (!checkbox) return;

    const enabled = checkbox.checked;

    try {
        const response = await fetch('/registration-settings', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${authToken}`
            },
            body: JSON.stringify({ enabled: enabled })
        });

        if (response.ok) {
            const data = await response.json();
            showToast(data.message, 'success');

            // 显示状态信息
            if (statusDiv && statusText) {
                statusText.textContent = data.message;
                statusDiv.style.display = 'block';

                // 3秒后隐藏状态信息
                setTimeout(() => {
                    statusDiv.style.display = 'none';
                }, 3000);
            }
        } else {
            const errorData = await response.json();
            showToast(`更新失败: ${errorData.detail || '未知错误'}`, 'danger');
        }
    } catch (error) {
        console.error('更新注册设置失败:', error);
        showToast('更新注册设置失败', 'danger');
    }
}

// 加载关键词未匹配回复设置
async function loadUnmatchReplySettings() {
    try {
        const response = await fetch(`${apiBase}/system-settings`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        if (response.ok) {
            const settings = await response.json();
            const textarea = document.getElementById('unmatchDefaultReply');
            if (textarea && settings.unmatch_default_reply) {
                textarea.value = settings.unmatch_default_reply;
            }
        }
    } catch (error) {
        console.error('加载关键词未匹配回复设置失败:', error);
    }
}

// 更新关键词未匹配回复设置
async function updateUnmatchReplySettings() {
    const textarea = document.getElementById('unmatchDefaultReply');
    const statusDiv = document.getElementById('unmatchReplyStatus');
    const statusText = document.getElementById('unmatchReplyStatusText');

    if (!textarea) return;

    const value = textarea.value.trim();
    if (!value) {
        showToast('请输入回复内容', 'warning');
        return;
    }

    try {
        const response = await fetch(`${apiBase}/system-settings/unmatch_default_reply`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${authToken}`
            },
            body: JSON.stringify({ 
                value: value,
                description: '关键词未匹配时的默认回复'
            })
        });

        if (response.ok) {
            showToast('关键词未匹配回复设置已更新', 'success');

            // 显示状态信息
            if (statusDiv && statusText) {
                statusText.textContent = '设置已更新';
                statusDiv.style.display = 'block';

                // 3秒后隐藏状态信息
                setTimeout(() => {
                    statusDiv.style.display = 'none';
                }, 3000);
            }
        } else {
            const errorData = await response.json();
            showToast(`更新失败: ${errorData.detail || '未知错误'}`, 'danger');
        }
    } catch (error) {
        console.error('更新关键词未匹配回复设置失败:', error);
        showToast('更新关键词未匹配回复设置失败', 'danger');
    }
}

// 加载门店引导话术设置
async function loadStoreGuideSettings() {
    try {
        const response = await fetch(`${apiBase}/system-settings`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        if (response.ok) {
            const settings = await response.json();
            const textarea = document.getElementById('storeGuideText');
            
            if (textarea && settings.store_guide_text) {
                textarea.value = settings.store_guide_text;
            } else if (textarea) {
                // 设置默认值
                textarea.value = '上述店铺是可用的，直接拍就行';
            }
        }
    } catch (error) {
        console.error('加载门店引导话术设置失败:', error);
    }
}

// 更新门店引导话术设置
async function updateStoreGuideSettings() {
    const textarea = document.getElementById('storeGuideText');
    const statusDiv = document.getElementById('storeGuideStatus');
    const statusText = document.getElementById('storeGuideStatusText');

    if (!textarea) return;

    const value = textarea.value.trim();
    if (!value) {
        showToast('请输入引导话术内容', 'warning');
        return;
    }

    try {
        const response = await fetch(`${apiBase}/system-settings/store_guide_text`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${authToken}`
            },
            body: JSON.stringify({ 
                value: value,
                description: '门店识别成功后的引导话术'
            })
        });

        if (response.ok) {
            const result = await response.json();
            
            // 构建成功消息
            let successMessage = '门店引导话术设置已更新';
            if (result.updated_keywords && result.updated_keywords > 0) {
                successMessage += `，已同时更新 ${result.updated_keywords} 个现有门店关键词`;
            }
            
            showToast(successMessage, 'success');

            // 显示状态信息
            if (statusDiv && statusText) {
                let statusMessage = '设置已更新';
                if (result.updated_keywords && result.updated_keywords > 0) {
                    statusMessage += `，更新了 ${result.updated_keywords} 个关键词`;
                }
                statusText.textContent = statusMessage;
                statusDiv.style.display = 'block';

                // 5秒后隐藏状态信息（给用户更多时间看到详细信息）
                setTimeout(() => {
                    statusDiv.style.display = 'none';
                }, 5000);
            }
        } else {
            const errorData = await response.json();
            showToast(`更新失败: ${errorData.detail || '未知错误'}`, 'danger');
        }
    } catch (error) {
        console.error('更新门店引导话术设置失败:', error);
        showToast('更新门店引导话术设置失败', 'danger');
    }
}

// 加载延迟引导话术设置
async function loadDelayedGuideSettings() {
    try {
        const response = await fetch(`${apiBase}/system-settings`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        if (response.ok) {
            const settings = await response.json();
            
            // 设置开关状态
            const enabledCheckbox = document.getElementById('delayedGuideEnabled');
            if (enabledCheckbox) {
                enabledCheckbox.checked = settings.delayed_guide_enabled === 'true';
            }
            
            // 设置延迟时间
            const delayInput = document.getElementById('delayedGuideDelay');
            if (delayInput && settings.delayed_guide_delay_seconds) {
                delayInput.value = settings.delayed_guide_delay_seconds;
            }
            
            // 设置话术内容
            const textarea = document.getElementById('delayedGuideText');
            if (textarea && settings.delayed_guide_text) {
                textarea.value = settings.delayed_guide_text;
            } else if (textarea) {
                // 设置默认值
                textarea.value = '亲，库存有限，如果有您要去的门店，请尽快下单哦';
            }
        }
    } catch (error) {
        console.error('加载延迟引导话术设置失败:', error);
    }
}

// 更新延迟引导话术设置
async function updateDelayedGuideSettings() {
    const enabledCheckbox = document.getElementById('delayedGuideEnabled');
    const delayInput = document.getElementById('delayedGuideDelay');
    const textarea = document.getElementById('delayedGuideText');
    const statusDiv = document.getElementById('delayedGuideStatus');
    const statusText = document.getElementById('delayedGuideStatusText');

    if (!enabledCheckbox || !delayInput || !textarea) return;

    const enabled = enabledCheckbox.checked;
    const delaySeconds = parseInt(delayInput.value);
    const text = textarea.value.trim();

    // 验证输入
    if (enabled && !text) {
        showToast('请输入延迟引导话术内容', 'warning');
        return;
    }

    if (enabled && (delaySeconds < 10 || delaySeconds > 3600)) {
        showToast('延迟时间必须在10-3600秒之间', 'warning');
        return;
    }

    try {
        // 批量更新所有设置
        const updates = [
            {
                key: 'delayed_guide_enabled',
                value: enabled ? 'true' : 'false',
                description: '是否启用延迟引导话术功能'
            },
            {
                key: 'delayed_guide_delay_seconds',
                value: delaySeconds.toString(),
                description: '延迟引导话术发送延迟时间（秒）'
            },
            {
                key: 'delayed_guide_text',
                value: text,
                description: '延迟引导话术内容'
            }
        ];

        const promises = updates.map(update => 
            fetch(`${apiBase}/system-settings/${update.key}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${authToken}`
                },
                body: JSON.stringify({ 
                    value: update.value,
                    description: update.description
                })
            })
        );

        const responses = await Promise.all(promises);
        const allSuccessful = responses.every(response => response.ok);

        if (allSuccessful) {
            const statusMessage = enabled ? '延迟引导话术功能已启用' : '延迟引导话术功能已禁用';
            showToast(statusMessage, 'success');

            // 显示状态信息
            if (statusDiv && statusText) {
                statusText.textContent = '设置已更新';
                statusDiv.style.display = 'block';

                // 3秒后隐藏状态信息
                setTimeout(() => {
                    statusDiv.style.display = 'none';
                }, 3000);
            }
        } else {
            showToast('部分设置更新失败', 'warning');
        }
    } catch (error) {
        console.error('更新延迟引导话术设置失败:', error);
        showToast('更新延迟引导话术设置失败', 'danger');
    }
}

// ================================
// 门店词库管理功能
// ================================

async function loadKeywordLibraries() {
    try {
        console.log('开始加载门店词库...');
        
        // 如果权限还没有加载，等待一下再重试
        if (currentUserPermissions === null) {
            setTimeout(() => loadKeywordLibraries(), 500);
            return;
        }
        
        const response = await fetchJSON('/keyword-libraries');
        console.log('门店词库API返回数据:', response);
        
        // 保存数据到全局变量
        allKeywordLibraries = response || [];
        
        renderKeywordLibraries(allKeywordLibraries);
        updateKeywordLibraryStats(allKeywordLibraries);
        
        // 根据权限控制创建库按钮显示 - 只有管理员才能创建库
        const createBtn = document.getElementById('createLibraryBtn');
        const isAdmin = currentUserInfo && currentUserInfo.is_admin;
        if (createBtn) {
            // 只有管理员才能看到创建库按钮
            if (isAdmin) {
                createBtn.style.display = 'inline-block';
            } else {
                createBtn.style.display = 'none';
            }
        }
    } catch (error) {
        console.error('加载门店词库失败:', error);
        showToast('加载门店词库失败: ' + error.message, 'error');
    }
}

async function fixKeywordLibraryStats() {
    try {
        const response = await fetchJSON('/keyword-libraries/fix-stats', {
            method: 'POST'
        });
        
        if (response.msg) {
            showToast('统计数据修复成功', 'success');
            // 重新加载门店词库列表
            await loadKeywordLibraries();
        }
    } catch (error) {
        console.error('修复统计数据失败:', error);
        showToast('修复统计数据失败: ' + error.message, 'error');
    }
}

function renderKeywordLibraries(libraries) {
    const container = document.getElementById('keywordLibrariesContainer');
    const isAdmin = currentUserInfo && currentUserInfo.is_admin;
    
    if (!libraries || libraries.length === 0) {
        const createButton = isAdmin ? 
            `<button class="btn btn-primary" onclick="showCreateLibraryModal()">
                <i class="bi bi-plus-lg me-1"></i>创建第一个门店词库
            </button>` : '';
        
        container.innerHTML = `
            <div class="text-center p-4 text-muted">
                <i class="bi bi-collection fs-1"></i>
                <p class="mt-2">暂无门店词库</p>
                ${createButton}
            </div>
        `;
        return;
    }
    
    const librariesHtml = libraries.map(library => `
        <div class="card mb-3 library-card" data-library-id="${library.id}">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <div class="d-flex align-items-center mb-2">
                            <h6 class="mb-0 me-3">${escapeHtml(library.name)}</h6>
                            <span class="badge bg-success ms-2">${parseInt(library.share_count) || 0} 次分享</span>
                            ${library.creator_name ? `<span class="badge bg-info ms-2">创建者: ${escapeHtml(library.creator_name)}</span>` : ''}
                        </div>
                        ${library.description ? `<p class="text-muted mb-2">${escapeHtml(library.description)}</p>` : ''}
                        <div class="text-muted small">
                            <i class="bi bi-clock me-1"></i>创建于 ${formatDateTime(library.created_at)}
                            ${library.updated_at !== library.created_at ? `<i class="bi bi-arrow-clockwise ms-3 me-1"></i>更新于 ${formatDateTime(library.updated_at)}` : ''}
                        </div>
                    </div>
                    <div class="col-md-4 text-end">
                        <div class="btn-group" role="group">
                            ${isAdmin ? `
                            <button class="btn btn-outline-primary btn-sm" onclick="viewLibraryDetail(${library.id})" title="查看详情">
                                <i class="bi bi-eye"></i>
                            </button>
                            ` : '<!-- 无查看详情权限 -->'}
                            <button class="btn btn-outline-success btn-sm" onclick="applyLibraryToAccount(${library.id})" title="应用到账号">
                                <i class="bi bi-share"></i>
                            </button>
                            ${(isAdmin && currentUserInfo && (currentUserInfo.is_admin || library.user_id === currentUserInfo.user_id)) ? `
                            <button class="btn btn-outline-danger btn-sm" onclick="deleteKeywordLibrary(${library.id})" title="删除">
                                <i class="bi bi-trash"></i>
                            </button>
                            ` : ''}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `).join('');
    
    container.innerHTML = librariesHtml;
}

// 搜索门店词库
function searchKeywordLibraries() {
    const searchInput = document.getElementById('librarySearchInput');
    const searchTerm = searchInput.value.toLowerCase().trim();
    
    if (!searchTerm) {
        // 如果搜索框为空，显示所有词库
        renderKeywordLibraries(allKeywordLibraries);
        updateKeywordLibraryStats(allKeywordLibraries);
        return;
    }
    
    // 过滤词库数据
    const filteredLibraries = allKeywordLibraries.filter(library => {
        const name = (library.name || '').toLowerCase();
        const description = (library.description || '').toLowerCase();
        
        return name.includes(searchTerm) || description.includes(searchTerm);
    });
    
    // 渲染过滤后的结果
    renderKeywordLibraries(filteredLibraries);
    updateKeywordLibraryStats(filteredLibraries);
}

// 清空搜索
function clearLibrarySearch() {
    const searchInput = document.getElementById('librarySearchInput');
    searchInput.value = '';
    renderKeywordLibraries(allKeywordLibraries);
    updateKeywordLibraryStats(allKeywordLibraries);
}

function updateKeywordLibraryStats(libraries) {
    console.log('更新门店词库统计数据，输入数据:', libraries);
    if (!libraries) {
        console.log('门店词库数据为空');
        return;
    }
    
    const totalLibraries = libraries.length;
    const totalShares = libraries.reduce((sum, lib) => {
        const count = parseInt(lib.share_count) || 0;
        console.log(`库 "${lib.name}" 分享次数: ${lib.share_count} -> ${count}`);
        return sum + count;
    }, 0);
    const recentUpdates = libraries.filter(lib => {
        const updateTime = new Date(lib.updated_at);
        const now = new Date();
        const diffDays = (now - updateTime) / (1000 * 60 * 60 * 24);
        return diffDays <= 7;
    }).length;
    
    console.log(`统计数据: 库数=${totalLibraries}, 分享次数=${totalShares}, 最近更新=${recentUpdates}`);
    
    document.getElementById('totalLibraries').textContent = totalLibraries;
    document.getElementById('recentUpdates').textContent = recentUpdates;
    document.getElementById('totalShares').textContent = totalShares;
}

function showCreateLibraryModal() {
    // 检查用户权限 - 只有管理员才能创建门店词库
    const isAdmin = currentUserInfo && currentUserInfo.is_admin;
    if (!isAdmin) {
        showToast('您没有权限创建门店词库', 'error');
        return;
    }
    
    document.getElementById('libraryName').value = '';
    document.getElementById('libraryDescription').value = '';
    
    // 重置创建方式为Excel导入
    document.getElementById('createMethodExcel').checked = true;
    document.getElementById('createMethodCrawler').checked = false;
    
    // 重置表单字段
    document.getElementById('libraryFileInput').value = '';
    document.getElementById('crawlerSkuId').value = '';
    document.getElementById('crawlerMtToken').value = '';
    
    // 重置进度显示
    document.getElementById('createLibraryProgress').style.display = 'none';
    const progressBar = document.getElementById('progressBar');
    const progressMessage = document.getElementById('progressMessage');
    
    progressBar.style.width = '0%';
    progressBar.textContent = '';
    progressBar.removeAttribute('data-last-update');
    progressMessage.textContent = '正在初始化...';
    progressMessage.removeAttribute('data-last-message');
    document.getElementById('progressTitle').textContent = '处理中...';
    
    // 显示/隐藏相应的区域
    toggleCreateMethodSections();
    
    // 添加创建方式切换事件监听器
    const excelRadio = document.getElementById('createMethodExcel');
    const crawlerRadio = document.getElementById('createMethodCrawler');
    
    // 移除之前的事件监听器（避免重复绑定）
    excelRadio.removeEventListener('change', toggleCreateMethodSections);
    crawlerRadio.removeEventListener('change', toggleCreateMethodSections);
    
    // 添加新的事件监听器
    excelRadio.addEventListener('change', toggleCreateMethodSections);
    crawlerRadio.addEventListener('change', toggleCreateMethodSections);
    
    const modal = new bootstrap.Modal(document.getElementById('createLibraryModal'));
    
    // 添加模态框关闭事件监听
    const modalElement = document.getElementById('createLibraryModal');
    modalElement.addEventListener('hide.bs.modal', function(e) {
        const progressDiv = document.getElementById('createLibraryProgress');
        if (progressDiv.style.display !== 'none') {
            // 有正在进行的任务，询问用户是否确认关闭
            if (!confirm('有任务正在进行中，关闭窗口不会停止任务。确认关闭吗？')) {
                e.preventDefault();
                return false;
            }
        }
    });
    
    modal.show();
}

function toggleCreateMethodSections() {
    const isExcel = document.getElementById('createMethodExcel').checked;
    const excelSection = document.getElementById('excelUploadSection');
    const crawlerSection = document.getElementById('crawlerSection');
    const createBtn = document.getElementById('createLibraryModalBtn');
    
    if (isExcel) {
        excelSection.style.display = 'block';
        crawlerSection.style.display = 'none';
        createBtn.innerHTML = '<i class="bi bi-file-earmark-excel me-1"></i>导入并创建';
    } else {
        excelSection.style.display = 'none';
        crawlerSection.style.display = 'block';
        createBtn.innerHTML = '<i class="bi bi-globe me-1"></i>抓取并创建';
    }
}

async function createKeywordLibrary() {
    try {
        // 检查用户权限 - 只有管理员才能创建门店词库
        const isAdmin = currentUserInfo && currentUserInfo.is_admin;
        if (!isAdmin) {
            showToast('您没有权限创建门店词库', 'error');
            return;
        }
        
        const name = document.getElementById('libraryName').value.trim();
        const description = document.getElementById('libraryDescription').value.trim();
        const createMethod = document.querySelector('input[name="createMethod"]:checked').value;
        
        if (!name) {
            showToast('请输入库名称', 'error');
            return;
        }
        
        // 根据创建方式进行不同的处理
        if (createMethod === 'excel') {
            // Excel文件导入方式
            const fileInput = document.getElementById('libraryFileInput');
            const file = fileInput.files[0];
            
            if (!file) {
                showToast('请选择Excel文件', 'error');
                return;
            }
            
            await createLibraryFromExcel(name, description, file);
        } else if (createMethod === 'crawler') {
            // 爬虫抓取方式
            const skuId = document.getElementById('crawlerSkuId').value.trim();
            const mtToken = document.getElementById('crawlerMtToken').value.trim();
            
            if (!skuId) {
                showToast('请输入SKU ID', 'error');
                return;
            }
            
            if (!mtToken) {
                showToast('请输入MT Token', 'error');
                return;
            }
            
            await createLibraryFromCrawler(name, description, skuId, mtToken);
        }
        
    } catch (error) {
        console.error('创建门店词库失败:', error);
        showToast('创建失败: ' + error.message, 'error');
    }
}

async function createLibraryFromExcel(name, description, file) {
    try {
        // 禁用创建按钮并显示加载状态
        const createBtn = document.getElementById('createLibraryModalBtn');
        const originalBtnText = createBtn.innerHTML;
        createBtn.disabled = true;
        createBtn.innerHTML = '<i class="bi bi-hourglass-split me-1"></i>导入中...';
        
        // 首先创建空的门店词库
        const createResponse = await fetchJSON('/keyword-libraries', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                name: name,
                description: description || ""
            })
        });
        
        if (!createResponse.library_id) {
            throw new Error('创建门店词库失败');
        }
        
        const libraryId = createResponse.library_id;
        
        // 然后使用Excel文件生成关键词并添加到词库
        const formData = new FormData();
        formData.append('file', file);
        
        const importResponse = await fetch(`${apiBase}/keyword-libraries/${libraryId}/import-excel`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${authToken}`
            },
            body: formData
        });
        
        // 恢复按钮状态
        createBtn.disabled = false;
        createBtn.innerHTML = originalBtnText;
        
        if (importResponse.ok) {
            const result = await importResponse.json();
            
            if (result.is_async) {
                // 异步处理，显示进度跟踪
                showToast(`开始处理 ${result.total_keywords} 个关键词，请稍候...`, 'info');
                // 恢复按钮状态，因为任务已经开始
                createBtn.disabled = false;
                createBtn.innerHTML = originalBtnText;
                await trackTaskProgress(result.task_id, '导入');
                bootstrap.Modal.getInstance(document.getElementById('createLibraryModal')).hide();
                loadKeywordLibraries();
            } else {
                // 同步处理完成
                showToast(`门店词库创建成功！共添加 ${result.added} 个关键词`, 'success');
                bootstrap.Modal.getInstance(document.getElementById('createLibraryModal')).hide();
                loadKeywordLibraries();
            }
        } else {
            const error = await importResponse.json();
            // 如果导入失败，删除已创建的空词库
            await fetch(`${apiBase}/keyword-libraries/${libraryId}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${authToken}`
                }
            });
            throw new Error(error.detail || '导入Excel文件失败');
        }
    } catch (error) {
        console.error('从Excel创建门店词库失败:', error);
        
        // 恢复按钮状态
        const createBtn = document.getElementById('createLibraryModalBtn');
        createBtn.disabled = false;
        const isExcel = document.getElementById('createMethodExcel').checked;
        createBtn.innerHTML = isExcel ? '<i class="bi bi-file-earmark-excel me-1"></i>导入并创建' : '<i class="bi bi-globe me-1"></i>抓取并创建';
        
        showToast('创建失败: ' + error.message, 'error');
    }
}

async function createLibraryFromCrawler(name, description, skuId, mtToken) {
    try {
        // 首先创建空的门店词库
        const createResponse = await fetchJSON('/keyword-libraries', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                name: name,
                description: description || ""
            })
        });
        
        if (!createResponse.library_id) {
            throw new Error('创建门店词库失败');
        }
        
        const libraryId = createResponse.library_id;
        
        // 禁用创建按钮并显示加载状态
        const createBtn = document.getElementById('createLibraryModalBtn');
        const originalBtnText = createBtn.innerHTML;
        createBtn.disabled = true;
        createBtn.innerHTML = '<i class="bi bi-hourglass-split me-1"></i>抓取中...';
        
        // 显示进度提示
        showToast('正在抓取门店信息，请稍候...', 'info');
        
        // 调用爬虫抓取API
        const crawlerResponse = await fetchJSON(`/keyword-libraries/${libraryId}/crawler-create`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                sku_id: skuId,
                mt_token: mtToken
            })
        });
        
        // 恢复按钮状态
        createBtn.disabled = false;
        createBtn.innerHTML = originalBtnText;
        
        if (crawlerResponse.success) {
            if (crawlerResponse.is_async) {
                // 异步处理，显示进度跟踪
                showToast('开始抓取门店信息，请稍候...', 'info');
                // 恢复按钮状态，因为任务已经开始
                createBtn.disabled = false;
                createBtn.innerHTML = originalBtnText;
                await trackTaskProgress(crawlerResponse.task_id, '抓取');
                bootstrap.Modal.getInstance(document.getElementById('createLibraryModal')).hide();
                loadKeywordLibraries();
            } else {
                // 同步处理完成
                showToast(`门店词库创建成功！共添加 ${crawlerResponse.added} 个关键词`, 'success');
                bootstrap.Modal.getInstance(document.getElementById('createLibraryModal')).hide();
                loadKeywordLibraries();
            }
        } else {
            // 如果抓取失败，删除已创建的空词库
            await fetch(`${apiBase}/keyword-libraries/${libraryId}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${authToken}`
                }
            });
            throw new Error(crawlerResponse.message || '爬虫抓取失败');
        }
    } catch (error) {
        console.error('从爬虫创建门店词库失败:', error);
        
        // 恢复按钮状态
        const createBtn = document.getElementById('createLibraryModalBtn');
        createBtn.disabled = false;
        const isExcel = document.getElementById('createMethodExcel').checked;
        createBtn.innerHTML = isExcel ? '<i class="bi bi-file-earmark-excel me-1"></i>导入并创建' : '<i class="bi bi-globe me-1"></i>抓取并创建';
        
        showToast('创建失败: ' + error.message, 'error');
    }
}

async function trackTaskProgress(taskId, taskType) {
    // 跟踪异步任务进度
    return new Promise((resolve, reject) => {
        let checkCount = 0;
        const maxChecks = 300; // 最多检查5分钟（300 * 1秒）
        
        // 显示进度区域
        const progressDiv = document.getElementById('createLibraryProgress');
        const progressTitle = document.getElementById('progressTitle');
        const progressBar = document.getElementById('progressBar');
        const progressMessage = document.getElementById('progressMessage');
        
        progressDiv.style.display = 'block';
        progressTitle.textContent = `${taskType}中...`;
        
        const checkProgress = async () => {
            try {
                checkCount++;
                
                // 使用原生fetch避免fetchJSON的loading效果
                const response = await fetch(`${apiBase}/keyword-libraries/task-status/${taskId}`, {
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }
                
                const data = await response.json();
                
                if (data.status === 'completed') {
                    // 隐藏进度显示
                    progressDiv.style.display = 'none';
                    showToast(`${taskType}完成！共添加 ${data.added} 个关键词到"${data.library_name}"`, 'success');
                    resolve(data);
                    return;
                } else if (data.status === 'failed') {
                    // 隐藏进度显示
                    progressDiv.style.display = 'none';
                    showToast(`${taskType}失败: ${data.message}`, 'error');
                    reject(new Error(data.message));
                    return;
                } else if (data.status === 'processing') {
                    // 更新进度显示（智能防抖优化）
                    const progress = Math.round((data.progress / data.total) * 100);
                    const currentWidth = parseInt(progressBar.style.width) || 0;
                    
                    // 智能更新策略：
                    // 1. 进度变化超过2%时更新
                    // 2. 或者消息内容发生变化时更新
                    // 3. 或者超过5秒没有更新时强制更新
                    const lastUpdate = progressBar.getAttribute('data-last-update') || 0;
                    const currentTime = Date.now();
                    const lastMessage = progressMessage.getAttribute('data-last-message') || '';
                    
                    const shouldUpdate = 
                        Math.abs(progress - currentWidth) >= 2 || 
                        data.message !== lastMessage || 
                        (currentTime - lastUpdate) > 5000;
                    
                    if (shouldUpdate) {
                        progressBar.style.width = `${progress}%`;
                        progressBar.textContent = `${progress}%`;
                        progressBar.setAttribute('data-last-update', currentTime);
                        progressMessage.textContent = `${data.message} (${data.progress}/${data.total})`;
                        progressMessage.setAttribute('data-last-message', data.message);
                    }
                    
                    // 继续检查
                    if (checkCount < maxChecks) {
                        setTimeout(checkProgress, 2000); // 进一步减少检查频率到2秒一次
                    } else {
                        progressDiv.style.display = 'none';
                        showToast(`${taskType}超时，请检查任务状态`, 'warning');
                        reject(new Error('任务超时'));
                    }
                }
            } catch (error) {
                console.error('检查任务状态失败:', error);
                if (checkCount < maxChecks) {
                    setTimeout(checkProgress, 3000); // 出错时3秒后重试
                } else {
                    progressDiv.style.display = 'none';
                    showToast(`${taskType}状态检查失败`, 'error');
                    reject(error);
                }
            }
        };
        
        // 开始检查
        checkProgress();
    });
}

async function viewLibraryDetail(libraryId) {
    try {
        const response = await fetchJSON(`/keyword-libraries/${libraryId}`);
        renderLibraryDetail(response, libraryId);
        
        // 加载账号列表
        await loadAccountsForLibrary();
        
        // 显示完整的模态框（包含关键词列表）
        showLibraryDetailModal(true);
    } catch (error) {
        console.error('加载门店词库详情失败:', error);
        showToast('加载详情失败: ' + error.message, 'error');
    }
}

async function showApplyLibraryModal(libraryId) {
    try {
        // 只加载账号列表，不加载关键词详情
        await loadAccountsForLibrary();
        
        // 设置当前库ID
        window.currentLibraryId = libraryId;
        
        // 显示简化的模态框（不包含关键词列表）
        showLibraryDetailModal(false);
    } catch (error) {
        console.error('加载应用设置失败:', error);
        showToast('加载应用设置失败: ' + error.message, 'error');
    }
}

function showLibraryDetailModal(showKeywordsList = true) {
    // 控制关键词列表的显示/隐藏
    const keywordsSection = document.querySelector('#libraryDetailModal .col-md-8');
    const applySection = document.querySelector('#libraryDetailModal .col-md-4');
    const modalTitle = document.querySelector('#libraryDetailModal .modal-title');
    
    if (showKeywordsList) {
        // 显示关键词列表，使用原来的布局
        keywordsSection.style.display = 'block';
        keywordsSection.className = 'col-md-8';
        applySection.className = 'col-md-4';
        modalTitle.innerHTML = '<i class="bi bi-collection me-2"></i>门店词库详情';
    } else {
        // 隐藏关键词列表，应用设置占满整行
        keywordsSection.style.display = 'none';
        applySection.className = 'col-md-12';
        modalTitle.innerHTML = '<i class="bi bi-share me-2"></i>应用门店词库到账号';
    }
    
    const modal = new bootstrap.Modal(document.getElementById('libraryDetailModal'));
    
    // 监听模态框关闭事件，重置布局
    const modalElement = document.getElementById('libraryDetailModal');
    modalElement.addEventListener('hidden.bs.modal', function () {
        // 重置为默认布局
        keywordsSection.style.display = 'block';
        keywordsSection.className = 'col-md-8';
        applySection.className = 'col-md-4';
        modalTitle.innerHTML = '<i class="bi bi-collection me-2"></i>门店词库详情';
    }, { once: true }); // 只执行一次
    
    modal.show();
}

function renderLibraryDetail(data, libraryId) {
    const tbody = document.getElementById('libraryKeywordsTableBody');
    
    if (!data.items || data.items.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="4" class="text-center text-muted">
                    <i class="bi bi-inbox"></i> 暂无关键词
                </td>
            </tr>
        `;
        return;
    }
    
    const rows = data.items.map(item => `
        <tr>
            <td><code>${escapeHtml(item.keyword)}</code></td>
            <td>${escapeHtml(item.reply)}</td>
            <td><span class="badge bg-${item.type === 'image' ? 'warning' : 'primary'}">${item.type || 'text'}</span></td>
        </tr>
    `).join('');
    
    tbody.innerHTML = rows;
    
    // 保存当前库ID
    window.currentLibraryId = libraryId;
}

async function loadAccountsForLibrary() {
    try {
        const response = await fetchJSON('/cookies/details');
        const select = document.getElementById('targetAccountSelect');
        
        select.innerHTML = '<option value="">请选择要应用的账号</option>';
        
        response.forEach(account => {
            const option = document.createElement('option');
            option.value = account.id;
            option.textContent = `${account.id}${account.remark ? ` (${account.remark})` : ''}`;
            select.appendChild(option);
        });
    } catch (error) {
        console.error('加载账号列表失败:', error);
    }
}

async function applyKeywordLibrary() {
    try {
        const libraryId = window.currentLibraryId;
        const targetAccount = document.getElementById('targetAccountSelect').value;
        const targetItemId = document.getElementById('targetItemIdInput').value.trim();
        
        if (!libraryId) {
            showToast('请先选择门店词库', 'error');
            return;
        }
        
        if (!targetAccount) {
            showToast('请选择目标账号', 'error');
            return;
        }
        
        if (!targetItemId) {
            showToast('请输入商品ID', 'error');
            return;
        }
        
        const response = await fetchJSON(`/keyword-libraries/${libraryId}/apply`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                cookie_id: targetAccount,
                item_id: targetItemId
            })
        });
        
        if (response.msg) {
            showToast(`应用成功，商品 ${targetItemId}`, 'success');
            bootstrap.Modal.getInstance(document.getElementById('libraryDetailModal')).hide();
            
            // 刷新当前账号的商品列表（延迟执行避免竞态条件）
            if (currentCookieId === targetAccount) {
                setTimeout(async () => {
                    await refreshKeywordsList();
                }, 100);
            }
        } else {
            showToast('应用失败: ' + (response.detail || '未知错误'), 'error');
        }
    } catch (error) {
        console.error('应用门店词库失败:', error);
        showToast('应用失败: ' + error.message, 'error');
    }
}

async function deleteKeywordLibrary(libraryId) {
    if (!confirm('确定要删除这个门店词库吗？删除后无法恢复。')) {
        return;
    }
    
    try {
        const response = await fetchJSON(`/keyword-libraries/${libraryId}`, {
            method: 'DELETE'
        });
        
        if (response.msg) {
            showToast('门店词库删除成功', 'success');
            loadKeywordLibraries();
        } else {
            showToast('删除失败: ' + (response.detail || '未知错误'), 'error');
        }
    } catch (error) {
        console.error('删除门店词库失败:', error);
        showToast('删除失败: ' + error.message, 'error');
    }
}

function applyLibraryToAccount(libraryId) {
    window.currentLibraryId = libraryId;
    
    // 检查用户权限，普通用户不显示关键词列表
    const isAdmin = currentUserInfo && currentUserInfo.is_admin;
    if (isAdmin) {
        // 管理员显示完整的详情页面
        viewLibraryDetail(libraryId);
    } else {
        // 普通用户只显示应用设置，不显示关键词列表
        showApplyLibraryModal(libraryId);
    }
}

// ================================
// 通用词库管理功能
// ================================

async function loadGlobalKeywords() {
    try {
        console.log('开始加载通用关键词...');
        const response = await fetchJSON('/global-keywords');
        console.log('通用关键词API返回数据:', response);
        renderGlobalKeywords(response);
        updateGlobalKeywordStats(response);
    } catch (error) {
        console.error('加载通用关键词失败:', error);
        showToast('加载通用关键词失败: ' + error.message, 'error');
    }
}

function renderGlobalKeywords(keywords) {
    const container = document.getElementById('globalKeywordsContainer');

    if (!keywords || keywords.length === 0) {
        container.innerHTML = `
            <div class="text-center p-4 text-muted">
                <i class="bi bi-globe fs-1"></i>
                <p class="mt-2">暂无通用关键词</p>
                <button class="btn btn-primary" onclick="document.getElementById('globalKeywordInput').focus()">
                    <i class="bi bi-plus-lg me-1"></i>添加第一个通用关键词
                </button>
            </div>
        `;
        return;
    }

    const keywordsHtml = keywords.map(keyword => `
        <div class="card mb-3">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-md-2">
                        <div class="d-flex align-items-center">
                            <span class="badge ${keyword.type === 'image' ? 'bg-info' : 'bg-primary'} me-2">
                                <i class="bi ${keyword.type === 'image' ? 'bi-image' : 'bi-chat-text'}"></i>
                                ${keyword.type === 'image' ? '图片' : '文本'}
                            </span>
                            ${keyword.is_fuzzy ? '<span class="badge bg-warning me-2"><i class="bi bi-asterisk"></i>模糊</span>' : ''}
                            <strong>${escapeHtml(keyword.keyword)}</strong>
                        </div>
                    </div>
                    <div class="col-md-5">
                        <div class="text-muted">
                            ${keyword.type === 'image' && keyword.image_url ?
                                `<img src="${keyword.image_url}" alt="关键词图片" style="max-width: 100px; max-height: 50px;" class="me-2">` :
                                ''
                            }
                            ${escapeHtml(keyword.reply)}
                        </div>
                    </div>
                    <div class="col-md-2">
                        <span class="badge ${keyword.enabled ? 'bg-success' : 'bg-secondary'}">
                            ${keyword.enabled ? '启用' : '禁用'}
                        </span>
                    </div>
                    <div class="col-md-2">
                        <small class="text-muted">${formatDateTime(keyword.created_at)}</small>
                    </div>
                    <div class="col-md-1">
                        <div class="btn-group">
                            <button class="btn btn-outline-primary btn-sm" onclick="editGlobalKeyword(${keyword.id})" title="编辑">
                                <i class="bi bi-pencil"></i>
                            </button>
                            <button class="btn btn-outline-${keyword.enabled ? 'warning' : 'success'} btn-sm"
                                onclick="toggleGlobalKeywordStatus(${keyword.id}, ${!keyword.enabled})"
                                title="${keyword.enabled ? '禁用' : '启用'}">
                                <i class="bi ${keyword.enabled ? 'bi-pause' : 'bi-play'}"></i>
                            </button>
                            <button class="btn btn-outline-danger btn-sm" onclick="deleteGlobalKeyword(${keyword.id})" title="删除">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `).join('');

    container.innerHTML = keywordsHtml;
}

function updateGlobalKeywordStats(keywords) {
    console.log('更新通用关键词统计数据，输入数据:', keywords);
    if (!keywords) {
        console.log('通用关键词数据为空');
        return;
    }

    const totalKeywords = keywords.length;
    const enabledKeywords = keywords.filter(k => k.enabled).length;
    const disabledKeywords = totalKeywords - enabledKeywords;

    // 计算今日新增（简单实现，实际可能需要更复杂的逻辑）
    const today = new Date().toISOString().split('T')[0];
    const recentKeywords = keywords.filter(k => k.created_at && k.created_at.startsWith(today)).length;

    document.getElementById('totalGlobalKeywords').textContent = totalKeywords;
    document.getElementById('enabledGlobalKeywords').textContent = enabledKeywords;
    document.getElementById('disabledGlobalKeywords').textContent = disabledKeywords;
    document.getElementById('recentGlobalKeywords').textContent = recentKeywords;
}

async function addGlobalKeyword() {
    try {
        const keyword = document.getElementById('globalKeywordInput').value.trim();
        const reply = document.getElementById('globalReplyInput').value.trim();
        const type = document.getElementById('globalKeywordType').value;
        const imageUrl = document.getElementById('globalImageUrlInput').value.trim();

        if (!keyword) {
            showToast('请输入关键词', 'error');
            return;
        }

        if (!reply && type === 'text') {
            showToast('请输入回复内容', 'error');
            return;
        }

        if (type === 'image' && !imageUrl) {
            showToast('图片类型关键词需要提供图片URL', 'error');
            return;
        }

        const response = await fetchJSON('/global-keywords', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                keyword: keyword,
                reply: reply,
                type: type,
                image_url: type === 'image' ? imageUrl : null
            })
        });

        if (response.msg) {
            showToast('通用关键词添加成功', 'success');
            // 清空输入框
            document.getElementById('globalKeywordInput').value = '';
            document.getElementById('globalReplyInput').value = '';
            document.getElementById('globalImageUrlInput').value = '';
            document.getElementById('globalKeywordType').value = 'text';
            document.getElementById('globalImageUrlGroup').style.display = 'none';
            // 重新加载列表
            loadGlobalKeywords();
        } else {
            showToast('添加失败: ' + (response.detail || '未知错误'), 'error');
        }
    } catch (error) {
        console.error('添加通用关键词失败:', error);
        showToast('添加失败: ' + error.message, 'error');
    }
}

async function editGlobalKeyword(keywordId) {
    try {
        // 获取当前关键词数据
        const keywords = await fetchJSON('/global-keywords');
        const keyword = keywords.find(k => k.id === keywordId);

        if (!keyword) {
            showToast('关键词不存在', 'error');
            return;
        }

        // 填充编辑表单
        document.getElementById('editGlobalKeywordId').value = keyword.id;
        document.getElementById('editGlobalKeywordInput').value = keyword.keyword;
        document.getElementById('editGlobalReplyInput').value = keyword.reply;
        document.getElementById('editGlobalKeywordType').value = keyword.type || 'text';
        document.getElementById('editGlobalImageUrlInput').value = keyword.image_url || '';

        // 显示/隐藏图片URL输入框
        const imageUrlGroup = document.getElementById('editGlobalImageUrlGroup');
        imageUrlGroup.style.display = keyword.type === 'image' ? 'block' : 'none';

        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('editGlobalKeywordModal'));
        modal.show();
    } catch (error) {
        console.error('获取关键词数据失败:', error);
        showToast('获取关键词数据失败: ' + error.message, 'error');
    }
}

async function updateGlobalKeyword() {
    try {
        const keywordId = document.getElementById('editGlobalKeywordId').value;
        const keyword = document.getElementById('editGlobalKeywordInput').value.trim();
        const reply = document.getElementById('editGlobalReplyInput').value.trim();
        const type = document.getElementById('editGlobalKeywordType').value;
        const imageUrl = document.getElementById('editGlobalImageUrlInput').value.trim();

        if (!keyword) {
            showToast('请输入关键词', 'error');
            return;
        }

        if (!reply && type === 'text') {
            showToast('请输入回复内容', 'error');
            return;
        }

        if (type === 'image' && !imageUrl) {
            showToast('图片类型关键词需要提供图片URL', 'error');
            return;
        }

        const response = await fetchJSON(`/global-keywords/${keywordId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                keyword: keyword,
                reply: reply,
                type: type,
                image_url: type === 'image' ? imageUrl : null
            })
        });

        if (response.msg) {
            showToast('通用关键词更新成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('editGlobalKeywordModal')).hide();
            loadGlobalKeywords();
        } else {
            showToast('更新失败: ' + (response.detail || '未知错误'), 'error');
        }
    } catch (error) {
        console.error('更新通用关键词失败:', error);
        showToast('更新失败: ' + error.message, 'error');
    }
}

async function deleteGlobalKeyword(keywordId) {
    if (!confirm('确定要删除这个通用关键词吗？删除后无法恢复。')) {
        return;
    }

    try {
        const response = await fetchJSON(`/global-keywords/${keywordId}`, {
            method: 'DELETE'
        });

        if (response.msg) {
            showToast('通用关键词删除成功', 'success');
            loadGlobalKeywords();
        } else {
            showToast('删除失败: ' + (response.detail || '未知错误'), 'error');
        }
    } catch (error) {
        console.error('删除通用关键词失败:', error);
        showToast('删除失败: ' + error.message, 'error');
    }
}

async function toggleGlobalKeywordStatus(keywordId, enabled) {
    try {
        const response = await fetchJSON(`/global-keywords/${keywordId}/toggle?enabled=${enabled}`, {
            method: 'PATCH'
        });

        if (response.msg) {
            const statusText = enabled ? '启用' : '禁用';
            showToast(`通用关键词${statusText}成功`, 'success');
            loadGlobalKeywords();
        } else {
            showToast('操作失败: ' + (response.detail || '未知错误'), 'error');
        }
    } catch (error) {
        console.error('切换通用关键词状态失败:', error);
        showToast('操作失败: ' + error.message, 'error');
    }
}

function showGlobalKeywordImportModal() {
    document.getElementById('globalKeywordImportData').value = '';
    const modal = new bootstrap.Modal(document.getElementById('globalKeywordImportModal'));
    modal.show();
}

function showGlobalKeywordExcelImportModal() {
    // 重置文件输入和预览
    document.getElementById('globalKeywordExcelFile').value = '';
    document.getElementById('globalKeywordExcelPreview').style.display = 'none';
    document.getElementById('globalKeywordExcelImportBtn').disabled = true;

    const modal = new bootstrap.Modal(document.getElementById('globalKeywordExcelImportModal'));
    modal.show();
}

// 全局变量存储Excel数据
let globalKeywordExcelData = [];

function handleGlobalKeywordExcelFile(input) {
    const file = input.files[0];
    if (!file) {
        document.getElementById('globalKeywordExcelPreview').style.display = 'none';
        document.getElementById('globalKeywordExcelImportBtn').disabled = true;
        return;
    }

    // 检查文件类型
    if (!file.name.match(/\.(xlsx|xls)$/i)) {
        showToast('请选择Excel文件（.xlsx或.xls格式）', 'error');
        input.value = '';
        return;
    }

    // 检查文件大小（限制为5MB）
    if (file.size > 5 * 1024 * 1024) {
        showToast('文件大小不能超过5MB', 'error');
        input.value = '';
        return;
    }

    // 读取Excel文件
    const reader = new FileReader();
    reader.onload = function(e) {
        try {
            // 使用SheetJS库解析Excel
            const data = new Uint8Array(e.target.result);
            const workbook = XLSX.read(data, { type: 'array' });

            // 获取第一个工作表
            const firstSheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[firstSheetName];

            // 转换为JSON数组
            const jsonData = XLSX.utils.sheet_to_json(worksheet, {
                header: 1,  // 使用数组格式而不是对象格式
                defval: ''  // 空单元格的默认值
            });

            // 处理数据
            globalKeywordExcelData = [];
            for (let i = 0; i < jsonData.length; i++) {
                const row = jsonData[i];
                if (row.length >= 2 && row[0] && row[1]) {
                    const keyword = String(row[0]).trim();
                    const reply = String(row[1]).trim();
                    if (keyword && reply) {
                        globalKeywordExcelData.push({
                            keyword: keyword,
                            reply: reply,
                            type: 'text'
                        });
                    }
                }
            }

            // 显示预览
            displayGlobalKeywordExcelPreview();

        } catch (error) {
            console.error('Excel文件解析失败:', error);
            showToast('Excel文件解析失败，请检查文件格式', 'error');
            input.value = '';
        }
    };

    reader.onerror = function() {
        showToast('文件读取失败', 'error');
        input.value = '';
    };

    reader.readAsArrayBuffer(file);
}

function displayGlobalKeywordExcelPreview() {
    const previewBody = document.getElementById('globalKeywordExcelPreviewBody');
    const countElement = document.getElementById('globalKeywordExcelCount');
    const importBtn = document.getElementById('globalKeywordExcelImportBtn');

    if (globalKeywordExcelData.length === 0) {
        previewBody.innerHTML = '<tr><td colspan="2" class="text-center text-muted">没有找到有效的关键词数据</td></tr>';
        countElement.textContent = '0';
        importBtn.disabled = true;
        document.getElementById('globalKeywordExcelPreview').style.display = 'block';
        return;
    }

    // 显示前10条数据作为预览
    const previewData = globalKeywordExcelData.slice(0, 10);
    const previewHtml = previewData.map(item => `
        <tr>
            <td>${escapeHtml(item.keyword)}</td>
            <td>${escapeHtml(item.reply)}</td>
        </tr>
    `).join('');

    previewBody.innerHTML = previewHtml;

    if (globalKeywordExcelData.length > 10) {
        previewBody.innerHTML += `
            <tr>
                <td colspan="2" class="text-center text-muted">
                    <i class="bi bi-three-dots"></i> 还有 ${globalKeywordExcelData.length - 10} 条数据...
                </td>
            </tr>
        `;
    }

    countElement.textContent = globalKeywordExcelData.length;
    importBtn.disabled = false;
    document.getElementById('globalKeywordExcelPreview').style.display = 'block';
}

async function importGlobalKeywordsFromExcel() {
    try {
        if (!globalKeywordExcelData || globalKeywordExcelData.length === 0) {
            showToast('没有可导入的数据', 'error');
            return;
        }

        // 显示导入进度
        const importBtn = document.getElementById('globalKeywordExcelImportBtn');
        const originalText = importBtn.textContent;
        importBtn.disabled = true;
        importBtn.innerHTML = '<i class="bi bi-hourglass-split me-1"></i>导入中...';

        const response = await fetchJSON('/global-keywords/batch', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                keywords: globalKeywordExcelData
            })
        });

        if (response.msg) {
            showToast(`Excel导入成功，共导入 ${globalKeywordExcelData.length} 个关键词`, 'success');
            bootstrap.Modal.getInstance(document.getElementById('globalKeywordExcelImportModal')).hide();
            loadGlobalKeywords();
        } else {
            showToast('导入失败: ' + (response.detail || '未知错误'), 'error');
        }
    } catch (error) {
        console.error('Excel导入失败:', error);
        showToast('导入失败: ' + error.message, 'error');
    } finally {
        // 恢复按钮状态
        const importBtn = document.getElementById('globalKeywordExcelImportBtn');
        importBtn.disabled = false;
        importBtn.textContent = '导入';
    }
}

async function importGlobalKeywords() {
    try {
        const data = document.getElementById('globalKeywordImportData').value.trim();

        if (!data) {
            showToast('请输入关键词数据', 'error');
            return;
        }

        const lines = data.split('\n').filter(line => line.trim());
        const keywords = [];

        for (const line of lines) {
            const parts = line.trim().split('|');
            if (parts.length >= 2) {
                keywords.push({
                    keyword: parts[0].trim(),
                    reply: parts[1].trim(),
                    type: 'text'
                });
            }
        }

        if (keywords.length === 0) {
            showToast('没有有效的关键词数据', 'error');
            return;
        }

        const response = await fetchJSON('/global-keywords/batch', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                keywords: keywords
            })
        });

        if (response.msg) {
            showToast(response.msg || `批量导入成功，共导入 ${keywords.length} 个关键词`, 'success');
            // 清空输入框
            document.getElementById('globalKeywordImportData').value = '';
            bootstrap.Modal.getInstance(document.getElementById('globalKeywordImportModal')).hide();
            loadGlobalKeywords();
        } else {
            showToast('导入失败: ' + (response.detail || '未知错误'), 'error');
        }
    } catch (error) {
        console.error('批量导入通用关键词失败:', error);
        showToast('导入失败: ' + error.message, 'error');
    }
}

async function exportGlobalKeywords() {
    try {
        const keywords = await fetchJSON('/global-keywords');

        if (!keywords || keywords.length === 0) {
            showToast('没有可导出的关键词', 'info');
            return;
        }

        const exportData = keywords.map(k => `${k.keyword}|${k.reply}`).join('\n');

        // 创建下载链接
        const blob = new Blob([exportData], { type: 'text/plain;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `通用关键词_${new Date().toISOString().split('T')[0]}.txt`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);

        showToast('关键词导出成功', 'success');
    } catch (error) {
        console.error('导出通用关键词失败:', error);
        showToast('导出失败: ' + error.message, 'error');
    }
}

async function toggleAllGlobalKeywords(enabled) {
    try {
        const keywords = await fetchJSON('/global-keywords');
        const targetKeywords = keywords.filter(k => k.enabled !== enabled);

        if (targetKeywords.length === 0) {
            const statusText = enabled ? '启用' : '禁用';
            showToast(`所有关键词都已${statusText}`, 'info');
            return;
        }

        const statusText = enabled ? '启用' : '禁用';
        if (!confirm(`确定要${statusText}所有通用关键词吗？这将影响 ${targetKeywords.length} 个关键词。`)) {
            return;
        }

        let successCount = 0;
        let failCount = 0;

        for (const keyword of targetKeywords) {
            try {
                await fetchJSON(`/global-keywords/${keyword.id}/toggle?enabled=${enabled}`, {
                    method: 'PATCH'
                });
                successCount++;
            } catch (error) {
                console.error(`切换关键词 ${keyword.id} 状态失败:`, error);
                failCount++;
            }
        }

        if (successCount > 0) {
            showToast(`成功${statusText} ${successCount} 个关键词${failCount > 0 ? `，失败 ${failCount} 个` : ''}`, 'success');
            loadGlobalKeywords();
        } else {
            showToast('操作失败', 'error');
        }
    } catch (error) {
        console.error('批量切换通用关键词状态失败:', error);
        showToast('操作失败: ' + error.message, 'error');
    }
}

function searchGlobalKeywords() {
    const searchTerm = document.getElementById('globalKeywordSearchInput').value.trim().toLowerCase();
    const cards = document.querySelectorAll('#globalKeywordsContainer .card');

    cards.forEach(card => {
        const keyword = card.querySelector('strong').textContent.toLowerCase();
        const reply = card.querySelector('.text-muted').textContent.toLowerCase();

        if (keyword.includes(searchTerm) || reply.includes(searchTerm)) {
            card.style.display = 'block';
        } else {
            card.style.display = 'none';
        }
    });
}

// 监听关键词类型变化，显示/隐藏图片URL输入框
document.addEventListener('DOMContentLoaded', function() {
    // 添加关键词表单
    const globalKeywordType = document.getElementById('globalKeywordType');
    if (globalKeywordType) {
        globalKeywordType.addEventListener('change', function() {
            const imageUrlGroup = document.getElementById('globalImageUrlGroup');
            if (imageUrlGroup) {
                imageUrlGroup.style.display = this.value === 'image' ? 'block' : 'none';
            }
        });
    }

    // 编辑关键词表单
    const editGlobalKeywordType = document.getElementById('editGlobalKeywordType');
    if (editGlobalKeywordType) {
        editGlobalKeywordType.addEventListener('change', function() {
            const imageUrlGroup = document.getElementById('editGlobalImageUrlGroup');
            if (imageUrlGroup) {
                imageUrlGroup.style.display = this.value === 'image' ? 'block' : 'none';
            }
        });
    }

    // 搜索框回车事件
    const searchInput = document.getElementById('globalKeywordSearchInput');
    if (searchInput) {
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchGlobalKeywords();
            }
        });
    }
    
    // 订单搜索框回车事件
    const orderSearchInput = document.getElementById('orderSearchInput');
    if (orderSearchInput) {
        orderSearchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchOrders();
            }
        });
    }

    // ================================
    // 订单管理相关功能
    // ================================
    
    // 订单管理全局变量
    let currentOrdersPage = 1;
    let totalOrdersPages = 0;
    let currentOrderData = null;
    
    // 显示订单管理页面时加载数据
    if (window.showSection) {
        const originalShowSection = window.showSection;
        window.showSection = function(sectionId) {
            originalShowSection(sectionId);
            if (sectionId === 'orders') {
                loadOrdersPage();
            }
        };
    }
});

// ================================
// 订单管理功能
// ================================

// 加载订单管理页面
async function loadOrdersPage() {
    try {
        // 加载账号列表到筛选器
        await loadOrderCookieFilter();
        // 加载订单统计
        await loadOrderStatistics();
        // 加载订单列表
        await loadOrders();
    } catch (error) {
        console.error('加载订单管理页面失败:', error);
        showToast('加载订单管理页面失败', 'error');
    }
}

// 加载账号筛选器
async function loadOrderCookieFilter() {
    try {
        const response = await fetch(`${apiBase}/api/cookies`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        if (!response.ok) {
            throw new Error('获取账号列表失败');
        }
        
        const data = await response.json();
        const cookieFilter = document.getElementById('orderCookieFilter');
        const addOrderCookieId = document.getElementById('addOrderCookieId');
        
        if (cookieFilter) {
            cookieFilter.innerHTML = '<option value="">所有账号</option>';
            data.cookies.forEach(cookie => {
                const option = document.createElement('option');
                option.value = cookie.id;
                option.textContent = cookie.id;
                cookieFilter.appendChild(option);
            });
        }
        
        if (addOrderCookieId) {
            addOrderCookieId.innerHTML = '<option value="">请选择账号</option>';
            data.cookies.forEach(cookie => {
                const option = document.createElement('option');
                option.value = cookie.id;
                option.textContent = cookie.id;
                addOrderCookieId.appendChild(option);
            });
        }
    } catch (error) {
        console.error('加载账号筛选器失败:', error);
    }
}

// 加载订单统计
async function loadOrderStatistics() {
    try {
        const cookieId = document.getElementById('orderCookieFilter')?.value || '';
        const url = cookieId ? 
            `${apiBase}/api/orders/statistics?cookie_id=${encodeURIComponent(cookieId)}` :
            `${apiBase}/api/orders/statistics`;
            
        const response = await fetch(url, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        if (!response.ok) {
            throw new Error('获取订单统计失败');
        }
        
        const data = await response.json();
        if (data.success) {
            const stats = data.data;
            
            // 更新统计卡片
            document.getElementById('totalOrders').textContent = stats.total_orders || 0;
            document.getElementById('pendingOrders').textContent = stats.status_counts['待发货'] || 0;
            document.getElementById('shippedOrders').textContent = stats.status_counts['已发货'] || 0;
            document.getElementById('monthAmount').textContent = `¥${(stats.month_amount || 0).toFixed(2)}`;
        }
    } catch (error) {
        console.error('加载订单统计失败:', error);
    }
}

// 加载订单列表
async function loadOrders(page = 1) {
    try {
        const cookieId = document.getElementById('orderCookieFilter')?.value || '';
        const status = document.getElementById('orderStatusFilter')?.value || '';
        const search = document.getElementById('orderSearchInput')?.value || '';
        const searchType = document.getElementById('orderSearchType')?.value || 'all';
        const pageSize = document.getElementById('ordersPageSize')?.value || 20;
        
        let url = `${apiBase}/api/orders?page=${page}&page_size=${pageSize}`;
        if (cookieId) url += `&cookie_id=${encodeURIComponent(cookieId)}`;
        if (status) url += `&status=${encodeURIComponent(status)}`;
        if (search) url += `&search=${encodeURIComponent(search)}`;
        if (searchType && searchType !== 'all') url += `&search_type=${encodeURIComponent(searchType)}`;
        
        const response = await fetch(url, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        if (!response.ok) {
            throw new Error('获取订单列表失败');
        }
        
        const data = await response.json();
        if (data.success) {
            displayOrders(data.data.orders);
            updateOrdersPagination(data.data.pagination);
            currentOrdersPage = page;
        } else {
            throw new Error(data.message || '获取订单列表失败');
        }
    } catch (error) {
        console.error('加载订单列表失败:', error);
        showToast('加载订单列表失败', 'error');
        
        // 显示错误状态
        const tbody = document.getElementById('ordersTableBody');
        if (tbody) {
            tbody.innerHTML = '<tr><td colspan="10" class="text-center text-muted">加载失败</td></tr>';
        }
    }
}

// 显示订单列表
function displayOrders(orders) {
    const tbody = document.getElementById('ordersTableBody');
    if (!tbody) return;
    
    if (!orders || orders.length === 0) {
        tbody.innerHTML = '<tr><td colspan="10" class="text-center text-muted">暂无订单数据</td></tr>';
        return;
    }
    
    tbody.innerHTML = orders.map(order => {
        const statusClass = getOrderStatusClass(order.order_status);
        const formattedTime = order.updated_at ? new Date(order.updated_at).toLocaleString() : '-';
        const couponCode = order.delivery_coupon_code || '-';
        const truncatedCouponCode = couponCode.length > 30 ? couponCode.substring(0, 30) + '...' : couponCode;
        
        // 订单号复制按钮
        const orderIdWithCopy = order.order_id ? 
            `<div class="d-flex align-items-center">
                <span class="me-2">${order.order_id}</span>
                <button class="btn btn-sm btn-outline-secondary" onclick="copyToClipboard(\`${order.order_id}\`, '订单号')" title="复制订单号">
                    <i class="bi bi-copy"></i>
                </button>
            </div>` : '-';
        
        // 券码复制按钮
        const couponCodeWithCopy = couponCode !== '-' ? 
            `<div class="d-flex align-items-center">
                <span class="me-2" title="${couponCode.replace(/"/g, '&quot;')}">${truncatedCouponCode}</span>
                <button class="btn btn-sm btn-outline-secondary" onclick="copyToClipboard(\`${couponCode.replace(/`/g, '\\`')}\`, '券码信息')" title="复制券码信息">
                    <i class="bi bi-copy"></i>
                </button>
            </div>` : '-';
        
        // 规格信息显示
        const specInfo = order.spec_name && order.spec_value ? 
            `<small class="text-muted">${order.spec_name}:</small><br>${order.spec_value}` : '-';
        
        // 数量显示
        const quantity = order.quantity || '-';
        
        // 金额显示
        const amount = order.amount ? `<span class="text-success fw-bold">¥${order.amount}</span>` : '-';
        
        return `
            <tr>
                <td>${orderIdWithCopy}</td>
                <td>${order.cookie_id || '-'}</td>
                <td>${order.buyer_name || order.buyer_id || '-'}</td>
                <td>${specInfo}</td>
                <td>${quantity}</td>
                <td>${amount}</td>
                <td><span class="badge ${statusClass}">${order.order_status || '-'}</span></td>
                <td>${couponCodeWithCopy}</td>
                <td>${formattedTime}</td>
                <td>
                    <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-primary" onclick="showOrderDetail('${order.order_id}', '${order.cookie_id}')" title="查看详情">
                            <i class="bi bi-eye"></i>
                        </button>
                        <button class="btn btn-outline-warning" onclick="showEditOrderModal('${order.order_id}', '${order.cookie_id}')" title="编辑">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-outline-danger" onclick="deleteOrder('${order.order_id}', '${order.cookie_id}')" title="删除">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    }).join('');
}

// 获取订单状态样式类
function getOrderStatusClass(status) {
    const statusClasses = {
        '待付款': 'bg-warning',
        '待发货': 'bg-info',
        '已发货': 'bg-primary',
        '已完成': 'bg-success',
        '退款中': 'bg-danger',
        '已退款': 'bg-secondary',
        '已取消': 'bg-dark'
    };
    return statusClasses[status] || 'bg-secondary';
}

// 更新订单分页
function updateOrdersPagination(pagination) {
    if (!pagination) return;
    
    currentOrdersPage = pagination.current_page;
    totalOrdersPages = pagination.total_pages;
    
    // 更新页面信息
    const pageInfo = document.getElementById('ordersPageInfo');
    if (pageInfo) {
        const start = (pagination.current_page - 1) * pagination.page_size + 1;
        const end = Math.min(start + pagination.page_size - 1, pagination.total_count);
        pageInfo.textContent = `显示第 ${start}-${end} 条，共 ${pagination.total_count} 条记录`;
    }
    
    // 更新页码输入框
    const pageInput = document.getElementById('ordersPageInput');
    if (pageInput) {
        pageInput.value = pagination.current_page;
    }
    
    // 更新总页数
    const totalPagesSpan = document.getElementById('ordersTotalPages');
    if (totalPagesSpan) {
        totalPagesSpan.textContent = pagination.total_pages;
    }
    
    // 更新按钮状态
    const firstPageBtn = document.getElementById('ordersFirstPage');
    const prevPageBtn = document.getElementById('ordersPrevPage');
    const nextPageBtn = document.getElementById('ordersNextPage');
    const lastPageBtn = document.getElementById('ordersLastPage');
    
    if (firstPageBtn) firstPageBtn.disabled = !pagination.has_prev;
    if (prevPageBtn) prevPageBtn.disabled = !pagination.has_prev;
    if (nextPageBtn) nextPageBtn.disabled = !pagination.has_next;
    if (lastPageBtn) lastPageBtn.disabled = !pagination.has_next;
}

// 订单分页跳转
function goToOrdersPage(page) {
    if (page < 1 || page > totalOrdersPages) return;
    loadOrders(page);
}

// 搜索订单
function searchOrders() {
    const searchInput = document.getElementById('orderSearchInput');
    const searchTypeSelect = document.getElementById('orderSearchType');
    const searchQuery = searchInput?.value?.trim() || '';
    const searchType = searchTypeSelect?.value || 'all';
    
    if (searchQuery) {
        // 显示搜索统计
        const searchStats = document.getElementById('orderSearchStats');
        const searchStatsText = document.getElementById('orderSearchStatsText');
        if (searchStats && searchStatsText) {
            const searchTypeText = searchType === 'all' ? '全部字段' : 
                                 searchType === 'order_id' ? '订单号' :
                                 searchType === 'buyer_name' ? '买家名称' :
                                 searchType === 'buyer_id' ? '买家ID' :
                                 searchType === 'item_title' ? '商品标题' :
                                 searchType === 'coupon_code' ? '券码' : '全部字段';
            searchStatsText.textContent = `搜索范围: ${searchTypeText}，关键词: "${searchQuery}"`;
            searchStats.style.display = 'block';
        }
    }
    
    loadOrders(1); // 重置到第一页
}

// 清除订单搜索
function clearOrderSearch() {
    const searchInput = document.getElementById('orderSearchInput');
    const searchTypeSelect = document.getElementById('orderSearchType');
    const cookieFilter = document.getElementById('orderCookieFilter');
    const statusFilter = document.getElementById('orderStatusFilter');
    const searchStats = document.getElementById('orderSearchStats');
    
    if (searchInput) searchInput.value = '';
    if (searchTypeSelect) searchTypeSelect.value = 'all';
    if (cookieFilter) cookieFilter.value = '';
    if (statusFilter) statusFilter.value = '';
    if (searchStats) searchStats.style.display = 'none';
    
    loadOrders(1);
}

// 刷新订单列表
function refreshOrders() {
    loadOrderStatistics();
    loadOrders(currentOrdersPage);
}

// 显示订单详情
async function showOrderDetail(orderId, cookieId) {
    try {
        const url = `${apiBase}/api/orders/${encodeURIComponent(orderId)}?cookie_id=${encodeURIComponent(cookieId)}`;
        const response = await fetch(url, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        if (!response.ok) {
            throw new Error('获取订单详情失败');
        }
        
        const data = await response.json();
        if (data.success) {
            const order = data.data;
            currentOrderData = order;
            
            // 填充订单详情
            document.getElementById('detailOrderId').textContent = order.order_id || '-';
            document.getElementById('detailCookieId').textContent = order.cookie_id || '-';
            document.getElementById('detailBuyerId').textContent = order.buyer_id || '-';
            document.getElementById('detailItemId').textContent = order.item_id || '-';
            document.getElementById('detailItemTitle').textContent = order.item_title || '-';
            
            // 新增的规格和数量信息
            document.getElementById('detailSpecName').textContent = order.spec_name || '-';
            document.getElementById('detailSpecValue').textContent = order.spec_value || '-';
            document.getElementById('detailQuantity').textContent = order.quantity || '-';
            
            const statusBadge = document.getElementById('detailOrderStatus');
            statusBadge.textContent = order.order_status || '-';
            statusBadge.className = `badge ${getOrderStatusClass(order.order_status)}`;
            
            // 更新金额显示逻辑，优先使用新的amount字段
            const amount = order.amount || order.order_amount;
            document.getElementById('detailOrderAmount').textContent = amount ? 
                (typeof amount === 'number' ? `¥${amount.toFixed(2)}` : `¥${amount}`) : '-';
            document.getElementById('detailCreatedAt').textContent = order.created_at ? new Date(order.created_at).toLocaleString() : '-';
            document.getElementById('detailUpdatedAt').textContent = order.updated_at ? new Date(order.updated_at).toLocaleString() : '-';
            document.getElementById('detailPaymentTime').textContent = order.payment_time ? new Date(order.payment_time).toLocaleString() : '-';
            document.getElementById('detailShippingTime').textContent = order.shipping_time ? new Date(order.shipping_time).toLocaleString() : '-';
            document.getElementById('detailDeliveryTime').textContent = order.delivery_time ? new Date(order.delivery_time).toLocaleString() : '-';
            document.getElementById('detailRefundTime').textContent = order.refund_time ? new Date(order.refund_time).toLocaleString() : '-';
            document.getElementById('detailBuyerMessage').textContent = order.buyer_message || '-';
            document.getElementById('detailSellerMessage').textContent = order.seller_message || '-';
            document.getElementById('detailShippingInfo').textContent = order.shipping_info || '-';
            
            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('orderDetailModal'));
            modal.show();
        } else {
            throw new Error(data.message || '获取订单详情失败');
        }
    } catch (error) {
        console.error('显示订单详情失败:', error);
        showToast('获取订单详情失败', 'error');
    }
}

// 编辑订单（从详情页面跳转）
function editOrder() {
    if (currentOrderData) {
        showEditOrderModal(currentOrderData.order_id, currentOrderData.cookie_id);
        // 关闭详情模态框
        const detailModal = bootstrap.Modal.getInstance(document.getElementById('orderDetailModal'));
        if (detailModal) {
            detailModal.hide();
        }
    }
}

// 显示编辑订单模态框
async function showEditOrderModal(orderId, cookieId) {
    try {
        const url = `${apiBase}/api/orders/${encodeURIComponent(orderId)}?cookie_id=${encodeURIComponent(cookieId)}`;
        const response = await fetch(url, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        if (!response.ok) {
            throw new Error('获取订单详情失败');
        }
        
        const data = await response.json();
        if (data.success) {
            const order = data.data;
            
            // 填充编辑表单
            document.getElementById('editOrderId').value = order.order_id || '';
            document.getElementById('editOrderCookieId').value = order.cookie_id || '';
            document.getElementById('editOrderBuyerId').value = order.buyer_id || '';
            document.getElementById('editOrderItemId').value = order.item_id || '';
            document.getElementById('editOrderItemTitle').value = order.item_title || '';
            document.getElementById('editOrderStatus').value = order.order_status || '';
            document.getElementById('editOrderAmount').value = order.order_amount || '';
            document.getElementById('editOrderBuyerMessage').value = order.buyer_message || '';
            document.getElementById('editOrderSellerMessage').value = order.seller_message || '';
            document.getElementById('editOrderShippingInfo').value = order.shipping_info || '';
            
            // 处理时间字段
            if (order.payment_time) {
                document.getElementById('editOrderPaymentTime').value = formatDateTimeLocal(order.payment_time);
            }
            if (order.shipping_time) {
                document.getElementById('editOrderShippingTime').value = formatDateTimeLocal(order.shipping_time);
            }
            if (order.delivery_time) {
                document.getElementById('editOrderDeliveryTime').value = formatDateTimeLocal(order.delivery_time);
            }
            if (order.refund_time) {
                document.getElementById('editOrderRefundTime').value = formatDateTimeLocal(order.refund_time);
            }
            
            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('editOrderModal'));
            modal.show();
        } else {
            throw new Error(data.message || '获取订单详情失败');
        }
    } catch (error) {
        console.error('显示编辑订单模态框失败:', error);
        showToast('获取订单信息失败', 'error');
    }
}

// 保存订单修改
async function saveOrderChanges() {
    try {
        const orderId = document.getElementById('editOrderId').value;
        const cookieId = document.getElementById('editOrderCookieId').value;
        
        const orderData = {
            buyer_id: document.getElementById('editOrderBuyerId').value,
            item_id: document.getElementById('editOrderItemId').value,
            item_title: document.getElementById('editOrderItemTitle').value,
            order_status: document.getElementById('editOrderStatus').value,
            order_amount: parseFloat(document.getElementById('editOrderAmount').value) || null,
            buyer_message: document.getElementById('editOrderBuyerMessage').value,
            seller_message: document.getElementById('editOrderSellerMessage').value,
            shipping_info: document.getElementById('editOrderShippingInfo').value,
            payment_time: document.getElementById('editOrderPaymentTime').value || null,
            shipping_time: document.getElementById('editOrderShippingTime').value || null,
            delivery_time: document.getElementById('editOrderDeliveryTime').value || null,
            refund_time: document.getElementById('editOrderRefundTime').value || null
        };
        
        const response = await fetch(`${apiBase}/api/orders/${encodeURIComponent(orderId)}?cookie_id=${encodeURIComponent(cookieId)}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${authToken}`
            },
            body: JSON.stringify(orderData)
        });
        
        const data = await response.json();
        if (data.success) {
            showToast('订单更新成功', 'success');
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('editOrderModal'));
            if (modal) {
                modal.hide();
            }
            
            // 刷新订单列表
            refreshOrders();
        } else {
            throw new Error(data.message || '订单更新失败');
        }
    } catch (error) {
        console.error('保存订单修改失败:', error);
        showToast('订单更新失败', 'error');
    }
}

// 手动添加订单
function addOrderManually() {
    // 清空表单
    document.getElementById('addOrderForm').reset();
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('addOrderModal'));
    modal.show();
}

// 保存新订单
async function saveNewOrder() {
    try {
        const form = document.getElementById('addOrderForm');
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }
        
        const orderData = {
            cookie_id: document.getElementById('addOrderCookieId').value,
            order_id: document.getElementById('addOrderId').value,
            buyer_id: document.getElementById('addOrderBuyerId').value,
            item_id: document.getElementById('addOrderItemId').value,
            item_title: document.getElementById('addOrderItemTitle').value,
            order_status: document.getElementById('addOrderStatus').value,
            order_amount: parseFloat(document.getElementById('addOrderAmount').value) || null,
            buyer_message: document.getElementById('addOrderBuyerMessage').value,
            seller_message: document.getElementById('addOrderSellerMessage').value
        };
        
        const response = await fetch(`${apiBase}/api/orders`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${authToken}`
            },
            body: JSON.stringify(orderData)
        });
        
        const data = await response.json();
        if (data.success) {
            showToast('订单创建成功', 'success');
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('addOrderModal'));
            if (modal) {
                modal.hide();
            }
            
            // 刷新订单列表
            refreshOrders();
        } else {
            throw new Error(data.message || '订单创建失败');
        }
    } catch (error) {
        console.error('保存新订单失败:', error);
        showToast('订单创建失败', 'error');
    }
}

// 删除订单
async function deleteOrder(orderId, cookieId) {
    if (!confirm('确定要删除这个订单吗？此操作不可撤销。')) {
        return;
    }
    
    try {
        const response = await fetch(`${apiBase}/api/orders/${encodeURIComponent(orderId)}?cookie_id=${encodeURIComponent(cookieId)}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        const data = await response.json();
        if (data.success) {
            showToast('订单删除成功', 'success');
            refreshOrders();
        } else {
            throw new Error(data.message || '订单删除失败');
        }
    } catch (error) {
        console.error('删除订单失败:', error);
        showToast('订单删除失败', 'error');
    }
}

// 格式化日期时间为本地输入格式
function formatDateTimeLocal(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day}T${hours}:${minutes}`;
}

// 测试订单解析功能
async function testOrderParsing() {
    // 使用您提供的示例消息数据
    const testMessage = {
        '1': {'1': {'1': '4132993444@goofish'}, '2': '49135414280@goofish', '3': '3680077795671.PNM', '4': 0, '5': 1756015032898, '6': {'1': 101, '3': {'1': '', '2': '[我已付款，等待你发货]', '3': '', '4': 26, '5': '{"contentType":26,"dxCard":{"item":{"main":{"clickParam":{"arg1":"MsgCard","args":{"source":"im","task_id":"4Ytd4BSQKIiz","msg_id":"c2cf1aa4395a42249e66358eb99bf7db"}},"exContent":{"bgColor":"#FFFFFF","button":{"bgColor":"#FFE60F","borderColor":"#FFE60F","clickParam":{"arg1":"MsgCardAction","args":{"source":"im","task_id":"4Ytd4BSQKIiz","msg_id":"c2cf1aa4395a42249e66358eb99bf7db"}},"fontColor":"#333333","targetUrl":"https://h5.m.goofish.com/wow/moyu/moyu-project/idle-logistics/pages/idleDeliver?kun=true&titleVisible=false&useCusFont=\'true\'&orderId=4700366427641994434","text":"去发货"},"desc":"请包装好商品，并按我在闲鱼上提供的地址发货","descColor":"#A3A3A3","title":"我已付款，等待你发货","upgrade":{"targetUrl":"https://h5.m.goofish.com/app/idleFish-F2e/fm-downlaod/home.html?noRedriect=true&canBack=true&checkVersion=true","version":"7.7.90"}},"targetUrl":"fleamarket://order_detail?id=4700366427641994434&role=Seller"}},"template":{"name":"idlefish_message_trade_chat_card","url":"https://dinamicx.alibabausercontent.com/pub/idlefish_message_trade_chat_card/1667222052767/idlefish_message_trade_chat_card.zip","version":"1667222052767"}}}'}}, '7': 1, '8': 1, '9': 0, '10': {'bizTag': '{"sourceId":"C2C:4Ytd4BSQKIiz","taskName":"付款完成待发货_卖家-正向升级","materialId":"4Ytd4BSQKIiz","taskId":"4Ytd4BSQKIiz"}', 'closePushReceiver': 'false', 'closeUnreadNumber': 'false', 'detailNotice': '[我已付款，等待你发货]', 'extJson': '{"msgArgs":{"task_id":"4Ytd4BSQKIiz","source":"im","msg_id":"c2cf1aa4395a42249e66358eb99bf7db"},"quickReply":"1","msgArg1":"MsgCard","updateKey":"49135414280:4700366427641994434:63:TRADE_PAID_DONE_SELLER:26","messageId":"c2cf1aa4395a42249e66358eb99bf7db","multiChannel":{"huawei":"EXPRESS","xiaomi":"108000","oppo":"EXPRESS","honor":"NORMAL","agoo":"product","vivo":"ORDER"},"contentType":"26","correlationGroupId":"4Ytd4BSQKIiz_drKxsv590jAX"}', 'receiver': '2206554483941', 'redReminder': '等待卖家发货', 'redReminderStyle': '1', 'reminderContent': '[我已付款，等待你发货]', 'reminderNotice': '请包装好商品，并按我在闲鱼上提供的地址发货', 'reminderTitle': '等待你发货', 'reminderUrl': 'fleamarket://message_chat?itemId=774438080478&peerUserId=4132993444&sid=49135414280&messageId=c2cf1aa4395a42249e66358eb99bf7db&adv=no', 'senderUserId': '4132993444', 'senderUserType': '0', 'sessionType': '1', 'updateHead': 'true'}, '12': 1}, '3': {'needPush': 'true'}
    };
    
    // 获取第一个可用的账号ID
    const cookieFilter = document.getElementById('orderCookieFilter');
    let testCookieId = '';
    if (cookieFilter && cookieFilter.options.length > 1) {
        testCookieId = cookieFilter.options[1].value; // 跳过"所有账号"选项
    }
    
    if (!testCookieId) {
        showToast('请先添加账号才能测试解析功能', 'warning');
        return;
    }
    
    try {
        const response = await fetch(`${apiBase}/api/orders/parse-message`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${authToken}`
            },
            body: JSON.stringify({
                cookie_id: testCookieId,
                message_data: testMessage
            })
        });
        
        const data = await response.json();
        if (data.success) {
            showToast(`测试成功！解析出订单: ${data.data.order_id}，状态: ${data.data.order_status}`, 'success');
            // 刷新订单列表以显示新解析的订单
            refreshOrders();
        } else {
            showToast(`测试失败: ${data.message}`, 'error');
        }
    } catch (error) {
        console.error('测试订单解析失败:', error);
        showToast('测试订单解析失败', 'error');
    }
}

// ================================
// 【商品管理 - 自动回复和自动发货设置】相关功能
// ================================

// 显示设置自动回复模态框
function showAutoReplyModal(cookieId, itemId) {
    // 设置商品信息
    document.getElementById('autoReplyAccountId').textContent = cookieId;
    document.getElementById('autoReplyItemId').textContent = itemId;
    
    // 清空表单
    document.getElementById('librarySearchInput').value = '';
    document.getElementById('librarySelect').innerHTML = '<option value="">请先搜索或加载词库列表</option>';
    document.getElementById('overwriteExisting').checked = false;
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('autoReplyModal'));
    modal.show();
}

// 显示设置自动发货模态框
function showAutoShippingModal(cookieId, itemId) {
    // 设置商品信息
    document.getElementById('autoShippingAccountId').textContent = cookieId;
    document.getElementById('autoShippingItemId').textContent = itemId;
    
    // 清空表单
    document.getElementById('cardSelect').innerHTML = '<option value="">请选择卡券</option>';
    document.getElementById('deliveryCount').value = 1;
    document.getElementById('generateImage').checked = true;
    document.getElementById('enableMultiSpec').checked = false;
    document.getElementById('specName').value = '';
    document.getElementById('specValue').value = '';
    document.getElementById('deliveryDescription').value = '';
    document.getElementById('multiSpecConfig').style.display = 'none';
    
    // 加载卡券列表
    loadCardsForAutoShipping();
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('autoShippingModal'));
    modal.show();
}

// 搜索门店词库
async function searchLibraries(searchTerm) {
    try {
        if (!searchTerm || searchTerm.trim().length < 1) {
            document.getElementById('librarySelect').innerHTML = '<option value="">请输入搜索关键词</option>';
            return;
        }
        
        const response = await fetch(`${apiBase}/keyword-libraries`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        if (response.ok) {
            const libraries = await response.json();
            const select = document.getElementById('librarySelect');
            select.innerHTML = '';
            
            // 过滤匹配的词库
            const filteredLibraries = libraries.filter(lib => 
                lib.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                (lib.description && lib.description.toLowerCase().includes(searchTerm.toLowerCase()))
            );
            
            if (filteredLibraries.length === 0) {
                select.innerHTML = '<option value="">未找到匹配的词库</option>';
            } else {
                filteredLibraries.forEach(library => {
                    const option = document.createElement('option');
                    option.value = library.id;
                    option.textContent = `${library.name} (${library.keyword_count || 0}个关键词)`;
                    if (library.description) {
                        option.title = library.description;
                    }
                    select.appendChild(option);
                });
            }
        } else {
            showToast('搜索词库失败', 'error');
        }
    } catch (error) {
        console.error('搜索词库失败:', error);
        showToast('搜索词库失败', 'error');
    }
}

// 加载所有门店词库
async function loadAllLibraries() {
    try {
        const response = await fetch(`${apiBase}/keyword-libraries`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        if (response.ok) {
            const libraries = await response.json();
            const select = document.getElementById('librarySelect');
            select.innerHTML = '';
            
            if (libraries.length === 0) {
                select.innerHTML = '<option value="">暂无可用的词库</option>';
            } else {
                libraries.forEach(library => {
                    const option = document.createElement('option');
                    option.value = library.id;
                    option.textContent = `${library.name} (${library.keyword_count || 0}个关键词)`;
                    if (library.description) {
                        option.title = library.description;
                    }
                    select.appendChild(option);
                });
            }
        } else {
            showToast('加载词库列表失败', 'error');
        }
    } catch (error) {
        console.error('加载词库列表失败:', error);
        showToast('加载词库列表失败', 'error');
    }
}

// 加载卡券列表用于自动发货设置
async function loadCardsForAutoShipping() {
    try {
        const response = await fetch(`${apiBase}/cards`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        if (response.ok) {
            const cards = await response.json();
            const select = document.getElementById('cardSelect');
            select.innerHTML = '<option value="">请选择卡券</option>';
            
            cards.forEach(card => {
                if (card.enabled) {
                    const option = document.createElement('option');
                    option.value = card.id;
                    
                    let displayText = card.name;
                    let typeText;
                    switch(card.type) {
                        case 'api':
                            typeText = 'API';
                            break;
                        case 'text':
                            typeText = '固定文字';
                            break;
                        case 'data':
                            typeText = '批量数据';
                            break;
                        case 'image':
                            typeText = '图片';
                            break;
                        default:
                            typeText = '未知类型';
                    }
                    displayText += ` (${typeText})`;
                    
                    option.textContent = displayText;
                    select.appendChild(option);
                }
            });
        } else {
            showToast('加载卡券列表失败', 'error');
        }
    } catch (error) {
        console.error('加载卡券列表失败:', error);
        showToast('加载卡券列表失败', 'error');
    }
}

// 应用自动回复设置
async function applyAutoReply() {
    try {
        const libraryId = document.getElementById('librarySelect').value;
        const accountId = document.getElementById('autoReplyAccountId').textContent;
        const itemId = document.getElementById('autoReplyItemId').textContent;
        const overwrite = document.getElementById('overwriteExisting').checked;
        
        if (!libraryId) {
            showToast('请选择门店词库', 'warning');
            return;
        }
        
        const response = await fetch(`${apiBase}/keyword-libraries/${libraryId}/apply`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${authToken}`
            },
            body: JSON.stringify({
                cookie_id: accountId,
                item_id: itemId,
                overwrite_existing: overwrite
            })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            showToast(`自动回复设置成功！应用了 ${data.applied_count} 个关键词`, 'success');
            bootstrap.Modal.getInstance(document.getElementById('autoReplyModal')).hide();
            
            // 如果当前正在查看该账号的关键词，刷新列表
            if (currentCookieId === accountId) {
                setTimeout(async () => {
                    await refreshKeywordsList();
                }, 500);
            }
        } else {
            showToast(data.message || '设置自动回复失败', 'error');
        }
    } catch (error) {
        console.error('设置自动回复失败:', error);
        showToast('设置自动回复失败', 'error');
    }
}

// 应用自动发货设置
async function applyAutoShipping() {
    try {
        const cardId = document.getElementById('cardSelect').value;
        const accountId = document.getElementById('autoShippingAccountId').textContent;
        const itemId = document.getElementById('autoShippingItemId').textContent;
        const deliveryCount = parseInt(document.getElementById('deliveryCount').value) || 1;
        const generateImage = document.getElementById('generateImage').checked;
        const enableMultiSpec = document.getElementById('enableMultiSpec').checked;
        const description = document.getElementById('deliveryDescription').value.trim();
        
        if (!cardId) {
            showToast('请选择卡券', 'warning');
            return;
        }
        
        const ruleData = {
            item_ids: [itemId],
            card_id: parseInt(cardId),
            delivery_count: deliveryCount,
            enabled: true,
            generate_image: generateImage,
            description: description || null
        };
        
        // 如果启用多规格，添加多规格配置
        if (enableMultiSpec) {
            const specName = document.getElementById('specName').value.trim();
            const specValue = document.getElementById('specValue').value.trim();
            
            if (specName && specValue) {
                ruleData.is_multi_spec = true;
                ruleData.spec_name = specName;
                ruleData.spec_value = specValue;
            }
        }
        
        const response = await fetch(`${apiBase}/delivery-rules`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${authToken}`
            },
            body: JSON.stringify(ruleData)
        });
        
        const data = await response.json();
        
        if (response.ok) {
            const message = data.created_count > 0 ? 
                `自动发货设置成功！创建了 ${data.created_count} 条发货规则` :
                '发货规则已存在，未创建新规则';
            showToast(message, 'success');
            bootstrap.Modal.getInstance(document.getElementById('autoShippingModal')).hide();
        } else {
            showToast(data.message || '设置自动发货失败', 'error');
        }
    } catch (error) {
        console.error('设置自动发货失败:', error);
        showToast('设置自动发货失败', 'error');
    }
}

// 多规格发货开关事件处理
document.addEventListener('DOMContentLoaded', function() {
    const enableMultiSpecCheckbox = document.getElementById('enableMultiSpec');
    const multiSpecConfig = document.getElementById('multiSpecConfig');
    
    if (enableMultiSpecCheckbox && multiSpecConfig) {
        enableMultiSpecCheckbox.addEventListener('change', function() {
            multiSpecConfig.style.display = this.checked ? 'block' : 'none';
        });
    }
});
